C# Linq to SQL:DataTable.Rows[0]["ColumnName"] 等效

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/187357/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 17:10:37  来源:igfitidea点击:

Linq to SQL: DataTable.Rows[0]["ColumnName"] equivalent

c#linqc#-3.0

提问by cllpse

Consider this:

考虑一下:

var query = from r in this._db.Recipes
            where r.RecipesID == recipeID
            select new { r.RecipesID, r.RecipesName };

How would i get individual columns in my queryobject without using a for-loop?

如何在query不使用 for 循环的情况下获取对象中的各个列?

Basicly: how do I translate DataTable.Rows[0]["ColumnName"]into Linq syntax?

基本上:我如何翻译DataTable.Rows[0]["ColumnName"]成 Linq 语法?

采纳答案by cllpse

This is the way to go about it:

这是解决问题的方法:

DataContext dc = new DataContext();

var recipe = (from r in dc.Recipes 
              where r.RecipesID == 1
              select r).FirstOrDefault();

if (recipe != null)
{
    id = recipe.RecipesID;
    name = recipe.RecipesName;
}

回答by Chris Shaffer

Sorry, misunderstood your question. As others are saying, you can use ToList() to get a List back. An alternative if all you need is the first one, just use:

对不起,误解了你的问题。正如其他人所说,您可以使用 ToList() 来获取列表。如果您只需要第一个,另一种选择,只需使用:


query.First().ColumnName

or if you want to avoid an exception on empty list:

或者如果您想避免空列表中的异常:


var obj = query.FirstOrDefault();
if (obj != null)
   obj.ColumnName;


Original Answer (so the comment makes sense):

原始答案(所以评论是有道理的):

Use Linq to Datasets. Basically would be something like:

使用Linq 到数据集。基本上是这样的:


var query = from r in yourTable.AsEnumerable()
select r.Field<string>("ColumnName");

回答by James Curran

It's really unclear what you are looking for, as your two samples are compatible.

由于您的两个样本是兼容的,因此您真的不清楚您在寻找什么。

As close as I can figure, what you want is:

尽我所能,你想要的是:

var rows = query.ToList();
string name = rows[0].RecipesName;

回答by Richard Poole

string name = this._db.Recipes.Single(r => r.RecipesID == recipeID).RecipesName;