如何使用LINQ从列表中返回单个值? [英] How do I return a single value from a list using LINQ?
问题描述
我是LINQ的新手,我知道这是(应该是?)一个简单的问题,但我正在努力解决简单LINQ查询的语法问题。以下简要说明代码显示了我想要实现的目标:
公共类水果
{
public int ID {get;组; } = 0;
public name {get;组; } = String.Empty;
}
公共类水果
{
公开列表< Fruit> ListOfFruits = new List< Fruit>()
{
new Fruit {ID = 0,Name =Apple},
new Fruit {ID = 1,Name =Orange},
new Fruit {ID = 2,Name =Banana},
}
public int GetIDFromName(string fruitName)
{
//什么去了吗?
}
}
作为初学者,我会感激任何建议。特别是,我想要一个使用特殊LINQ关键字('select','where'等)以及标准C#LINQ函数(Select(),Where()等)的解决方案,所以我可以比较两种方法。
似乎很少有例子将这两种方法并排显示出来进行比较,我也很困惑一种方法何时更好比另一个。为了简单的一致性,我想选择一种方式并坚持下去。
亲切的愿望~Patrick
我尝试过的事情:
我尝试过像......
ListOfFruits.Select(f = > f.ID).Where(...)
...但是我甚至无法编译它,因为它似乎只是在选择中指定了ID我不再能够在 Where 子句中引用名称。
ListOfFruits。 FirstOrDefault(x = > x.Name == Apple)。ID
您还可以将FirstOrDefault加载到对象中,并在尝试访问ID之前检查null。
根据建议,为了避免NullRef异常,你可以做一个偶然例如:
如果你在Roslyn编译器中使用VS版本:
< pre lang =c#> ListOfFruits.FirstOrDefault(x = > x.Name == < span class =code-string> Apple)?。ID
否则更详细的方法:
var fruit = ListOfFruits.FirstOrDefault(x = > x.Name == Apple);
if (fruit!= null )
{
return fruit.ID;
}
返回 0 ;
这不是通往罗马的唯一途径,您也可以使用Single(),SingleOrDefault()或First()。 Single希望单个响应必须存在,我发现自己更倾向于倾向于FirstOrDefault。
因为你要求两种语法形式:
< pre lang =c#> public int GetIDFromName( string fruitName)
{
// LINQ函数:
Fruit f = ListOfFruits.FirstOrDefault(x = > x.Name == fruitName);
// LINQ SQL-ish:
Fruit f =(来自 x ListOfFruits 其中 x.Name == fruitName 选择 x).FirstOrDefault();
// (两者都相同):
return f!= null ? f.ID:-1; // 一些值表示没有这样的水果
}这个将一种语法与另一种语法进行比较并不是一个特别好的例子......
我们也可以用户而不是FirstOrDefault.We可以像这样编写上面的代码
public int GetIDFromName(string fruitName)
{
// LINQ函数:
Fruit f = ListOfFruits.First(x => x.Name == fruitName);
// LINQ SQL-ish:
Fruit f =(来自ListOfFruits中的x,其中x。名称== fruitName选择x).First();
//(两者共通):
返回f!= null? f.ID:-1; //某些值表示没有这样的水果
}
I am a newbie to LINQ and I am aware this is (should be?) a simple question, but I am struggling with the syntax of a simple LINQ query. The following cut-down code shows what I am trying to achieve:
public class Fruit { public int ID { get; set; } = 0; public Name { get; set; } = String.Empty; } public class Fruits { public List<Fruit> ListOfFruits = new List<Fruit>() { new Fruit { ID = 0, Name = "Apple" }, new Fruit { ID = 1, Name = "Orange" }, new Fruit { ID = 2, Name = "Banana" }, } public int GetIDFromName( string fruitName ) { // What goes here? } }
As a beginner at this, I'd appreciate any advice at all. In particular, I would like a solution that uses the special LINQ keywords ('select', 'where', etc.) and also the standard C# LINQ functions ( Select(), Where(), etc.) so I can compare the two approaches.
There seems to be very few examples that show the two approaches side-by-side for comparison, and I am also confused about when one approach is better than the other. For simple consistency, I'd like to pick one way and stick with it.
Kind wishes ~ Patrick
What I have tried:
I have tried expressions like...
ListOfFruits.Select( f => f.ID ).Where( ... )
...but I can't even get this to compile because it seems by specifying just the ID in the Select clause, I stop myself being able to reference the Name in the Where clause.
ListOfFruits.FirstOrDefault(x => x.Name == "Apple").ID
You could also load the FirstOrDefault into an object and check for null before trying to access the id.
As suggested, in order to avoid a NullRef exception you can do a couple of things:
If you are using a version of VS with the Roslyn compiler:
ListOfFruits.FirstOrDefault(x => x.Name == "Apple")?.ID
Otherwise the more verbose method:
var fruit = ListOfFruits.FirstOrDefault(x => x.Name == "Apple"); if (fruit != null) { return fruit.ID; } return 0;
This is not the only road to Rome, you can also use Single(), SingleOrDefault() or First(). Single expects a single response that has to be there, I find myself gravitating to FirstOrDefault more often than not.
Since you asked for both syntax forms:
public int GetIDFromName( string fruitName ) { // LINQ functions: Fruit f = ListOfFruits.FirstOrDefault(x => x.Name == fruitName); // LINQ SQL-ish: Fruit f = (from x in ListOfFruits where x.Name == fruitName select x).FirstOrDefault(); // (common to both): return f != null ? f.ID : -1; // some value to indicate no such fruit }This is not a particularly good case for comparing one syntax with the other...
We can also user First instead of FirstOrDefault.We can write the above code like this
public int GetIDFromName( string fruitName )
{
// LINQ functions:
Fruit f = ListOfFruits.First(x => x.Name == fruitName);
// LINQ SQL-ish:
Fruit f = (from x in ListOfFruits where x.Name == fruitName select x).First();
// (common to both):
return f != null ? f.ID : -1; // some value to indicate no such fruit
}
这篇关于如何使用LINQ从列表中返回单个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!