0

我有 3 个类型的列表cab。我需要比较 listAlistB。如果Car-numberor statusin与 inlistB相同,listA那么我必须将该行添加listBlistC' else add it tolistA . I need to perform that same operation for all rows forlistB`。如何在两个列表上编写 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

4 回答 4

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);
}
于 2013-03-01T05:27:38.657 回答
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);
      }
   }
);
于 2013-03-01T05:40:00.390 回答
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));
于 2013-03-01T05:40:20.380 回答
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());

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

于 2017-05-31T04:11:07.497 回答