[英]Using Linq to object, how can I get one field's value based on another in the same list
I have a class that is defined as following: 我有一个定义如下的类:
public class MyClass
{
public int ID { get; set; }
public string Name { get; set; }
}
Then I have a logic where I build a list of that class: 然后,我有一个逻辑在其中建立该类的列表:
MyList = new List<MyClass>;
foreach(MyClassData myClass in Service.MyClassList)
{
MyList.Add(new MyClass{ID = myClass.ID, Name = myClass.Name});
}
Now, I need to get an 'ID' based on the 'Name'. 现在,我需要基于“名称”获得一个“ ID”。
I'm trying the following: 我正在尝试以下方法:
int id01 = MyList.Where(x => x.FileName.Equals("File01")).Single(x => x.FileID)
Doing that I'm getting an error message: 这样做,我收到一条错误消息:
Cannot implicitly convert type 'int' to 'bool'
无法将类型'int'隐式转换为'bool'
How would I do that using LINQ? 我将如何使用LINQ做到这一点?
The Single
method's is: Single
方法是:
public static TSource Single<TSource>( this IEnumerable<TSource> source, Func<TSource, bool> predicate )
It gets a predicate that should return a boolean but you are returning an integer. 它得到一个谓词,该谓词应返回布尔值,但您将返回一个整数。 It is used for filtering and not projecting.
它用于过滤而不是投影。
What you are looking for is: 您正在寻找的是:
int id01 = MyList.Single(x => x.FileName.Equals("File01")).FileID;
Or better use SingleOrDefault
: 或更好地使用
SingleOrDefault
:
int id01 = MyList.SingleOrDefault(x => x.FileName.Equals("File01"))?.FileID;
Also see if you want the SingleOrDefault
or the FirstOrDefault
另请参阅是否要使用
SingleOrDefault
或FirstOrDefault
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.