繁体   English   中英

根据ID从列表中查找项目

[英]Find an item from a list based on an ID

我有这堂课

public class item
{
        public int itemID { get; set; }
        public int itemValue { get; set; }
}

而且我有一个变量

public List<item> itemList;

我正在尝试使用lambda在itemList中搜索具有itemID = i的项目。 通常,没有lamda的函数如下:

public item FindItem(int i)
{
foreach (var t in itemList)
{
  if (t.itemID==i)
    return t;
}
return null;
}

我试图用这个lambda替换它

item Item = itemList.Where(x=>x.itemID==i).Select(x=>x);

我收到一个错误消息:

Error   1 Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<item>' to 'item'. An explicit conversion exists (are you missing a cast?)

我该如何纠正? 我仍在学习Lambda,Linq

由于如果找不到任何项目,则返回null ,因此请使用下一个代码作为等效代码:

public item FindItem(int i)
{
    return itemList.FirstOrDefault(item => item.itemId == i);
}

FirstOrDefault描述为Returns the first element of a sequence, or a default value if the sequence contains no elements. ,则Returns the first element of a sequence, or a default value if the sequence contains no elements. msdn )。

item type是一个类,因此默认值为null

您正在使用Select after Where子句,它基本上是过滤后的投影。 它采用类型A的序列,并返回类型B的序列。 您需要折叠一个序列,换句话说就是找到一个符合某些条件的项目。 LINQ中有很多折叠查询( FirstSingleMaxLastAggregate等),它们都从A类型的序列中返回A类型的A FirstOrDefault似乎非常适合您当前的C#实现。

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM