如何根据两个条件从通用列表中获取项目?

How can I get an item from a generic list based on two conditions?

我有一个自定义类型的通用列表,我正在尝试从中取回一个类型实例。我已经尝试了 "FirstOrDefault" 和 "Where" 使用两个必须为真的条件,但它们都给了我相同的错误消息 ("Operator '&&' cannot be applied to operands of type 'lambda expression' and 'lambda expression'")

他们在这里:

// FirstOrDefault
UnitItemCodeItemID uicii = 
    unitItemCodeItemIDList
        .FirstOrDefault((u => u.Unit == _unit) && (d => d.Description == desc));


// Where
UnitItemCodeItemID uicii = 
    unitItemCodeItemIDList
        .Where((u => u.Unit == _unit) && (d => d.Description == desc));

我不知道它是否相关,但 class 是:

public class UnitItemCodeItemID
{
    public string Unit { get; set; }
    public string Description { get; set; }
    public string ItemCode { get; set; }
    public int ItemID { get; set; }
}

您需要提供一个封装这两个条件的 lambda 表达式

.Where(p => p.Unit == _unit && p.Description == desc);

您之前的尝试是尝试将两个单独的 lambda 表达式与 and 语句结合起来。

您只需提供一个 lambda:

UnitItemCodeItemID uicii = unitItemCodeItemIDList
    .FirstOrDefault(obj => obj.Unit == _unit && obj.Description == desc);

这样想:这就像在函数中编写 foreach 循环一样。像这样:

public UnitItemCodeItemID ExtractFirst(IEnumerable<UnitItemCodeItemID> unitItemCodeItemIDList)
{
    foreach(var obj in unitItemCodeItemIDList)
    {
        if (obj.Unit == _unit && obj.Description == desc)
            return obj;
    }
    return null;
}

你的lamba必须提供"if"部分,剩下的在Linq实现中。