Lambda比较两个列表

时间:2013-03-01 05:08:58

标签: c# asp.net linq

我有3个cab类型的列表。我需要比较listAlistB。如果Car-number中的statuslistBlistA中的相同,那么我必须将listB中的该行添加到listC' else add it to listA . I need to perform that same operation for all rows for listB`。如何在两个列表上编写lambda来执行此操作?

这是我到目前为止的代码:

public class cab
{
    public string Name {get;set;}
    public string Desc {get;set;}
    public int Car_number   {get;set;}
    public bool status {get;set;}

}
cab c1 = new cab() { Name = "Zen",Desc = "äsdasdf",Car_number= "8832",status="false"};
cab c2 = new cab() { Name = "Ford",Desc = "sdfgedasdf",Car_number= "1132",status="true"};
cab c3 = new cab() { Name = "Swift",Desc = "sdsdf",Car_number= "732",status="true"};

List<cab> listA = new List<cab>();

listA.Add(c1);
listA.Add(c2);
listA.Add(c3);


List<cab> listB  = new List<cab>();
cab c4 = new cab() { Name = "Santro",Desc = "iisdasdf",Car_number= "8832",status="false"};
cab c5 = new cab() { Name = "Ritz",Desc = "esddf",Car_number= "132",status="true"};

listB.Add(c4);
listB.Add(c5);
List<cab> listC  = new List<cab>();

4 个答案:

答案 0 :(得分:3)

需要lambda的任何具体原因?

这对你有用吗?

foreach (var bItem in listB)
{
    if (listA.Any(aItem => bItem.Car_number == aItem.Car_number || bItem.status == aItem.status))
        listC.Add(bItem);
    else
        listA.Add(bItem);
}

答案 1 :(得分:0)

listB.ForEach(b =>
   {
      if (listA.Any(a => a.Car_number == b.Car_number || a.status == b.status))
      {
         listC.Add(b);
      }
      else
      {
         listA.Add(b);
      }
   }
);

答案 2 :(得分:0)

如果你想要实际的lambda表达式,试试这个:

    public static void ChoiseAndAdd(Cab cab,ref List<Cab> listA,ref List<Cab> listC)
    {
        if (listA.Any(e => e.Car_number == cab.Car_number) || listA.Any(e => e.status == cab.status))
        {
            listC.Add(cab);
            return;
        }
        listA.Add(user);
    }

和表达式:

listB.ForEach(e => ChoiseAndAdd(e, ref listA, ref listC));

答案 3 :(得分:0)

//Populate list C
listC = listA.Where(a=>  listB.Select(b=>b.Car_number).Contains(a.Car_number) && listB.Select(b => b.status).Contains(a.status)).ToList();
//Populate ListB using ListC
listB.AddRange(listA.Where(a => ! listC.Select(c => c.Car_number).Contains(a.Car_number) && ! listC.Select(c => c.status).Contains(a.status)).ToList());

注意:我偶然发现了类似的问题,并使用您的代码澄清了我的疑问。我知道这是一个老问题,答案已经提供(并被接受)。但我想我会为其他可能来这里寻找答案的人发布上述解决方案。