带有AddRange和Contains and Select的Linq ForEach

本文关键字:Linq ForEach Select and AddRange Contains 带有 | 更新日期: 2023-09-27 18:20:02

我有一个foreach循环,我正试图将其转换为linq查询

List<CustomType> typeList=new List<CustomType>();
List<int> ListID=new List<int>();
foreach (Info info in SubDetails)
{
    if (typeList.Contains(info.TypeID))
    {
        ListID.Add(info.OrderID);
    }
}

现在我正试图把它变成一个linq循环

 SubDetails.ForEach(u => List.AddRange(
                    typeList.Contains(ID or something)
                    .Select(u.OrderID)));

但这显然不起作用,请引导我朝着正确的方向

带有AddRange和Contains and Select的Linq ForEach

试试这个:

var ListID = SubDetails
                .Where(info => typeList.Any(type => type == info.TypeID)
                .Select(info => info.OrderID);

试试这个。

var ListID = typelist.Join(SubDetails,tl=>tl,sd=>sd.TypeID,(tl,sd)=>sd.OrderID).ToArray();

您可以将ListID填写为

SubDetails.Where(t => typeList.Exists(lst => lst.XXX == t.TypeID)).Select(id => id.OrderID)