简体   繁体   English

使用Linq进行反对,我如何才能基于同一列表中的另一个字段来获取一个字段的值

[英]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 另请参阅是否要使用SingleOrDefaultFirstOrDefault

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何获得列表中多于一列的总计并将其使用LINQ放入对象中? - How can I get totals for more than one column in a list and put this into an object using LINQ? c#如何使用LINQ根据另一个列表中的值获取列表中的值计数 - c# How to get count of value in a List based on value in another List using LINQ 我如何使用Linq在对象列表中按小时获取最大值 - How can I get the maximum value by hour in a list of object using Linq 如果我不能直接修改类,如何使用元素类型的字段值从另一个列表中删除列表? - How can I remove a list from another list using a field value of the element's type if i can't modify the class directly? 如何将一个列表的一个字段值更新为另一个列表的另一个相同字段? - How to Update one field value of one list into another same field of another one list? 如何根据其中的列表值使用linq过滤列表? - How can I filter a List with linq based on a value of a list within? 如何根据另一个 LINQ 查询过滤结果? - How can I filter results of one LINQ query based on another? 使用 LINQ 根据 C# 中的属性值搜索嵌套在另一个列表中的列表中的项目? - Searching for an item in a list that's nested inside another list based on a property value in C# using LINQ? 如何使用LINQ中的列表搜索字段的部分内容? - How can i search partial part of a field using a list in LINQ? 如何基于该对象的两个成员的值从通用列表中检索该对象? - How can I retrieve an object from a generic list based on the value of two of that object's members?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM