Linq ForEach with AddRange and Contains And Select

时间:2012-01-11 06:06:51

标签: c# linq lambda foreach

我有一个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)));

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

3 个答案:

答案 0 :(得分:1)

试试这个:

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

答案 1 :(得分:1)

您可以将ListID填充为

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

答案 2 :(得分:1)

试试这个。

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