看一下这个:
public class MyEntity
{
public string Name { get; set; }
public int Value { get; set; }
}
public static class MyEntityListExtension
{
public static List<MyEntity> AddList(this List<MyEntity> FirstList, List<MyEntity> SecondList)
{
List<MyEntity> ReturnList = new List<MyEntity>();
foreach (MyEntity CurrentEntity in FirstList)
{
MyEntity TempEntity = SecondList.Where<MyEntity>(x => x.Name.Equals(CurrentEntity.Name)).SingleOrDefault<MyEntity>();
if (TempEntity != null)
{
ReturnList.Add(new MyEntity()
{
Name = CurrentEntity.Name,
Value = CurrentEntity.Value + TempEntity.Value
});
}
}
return ReturnList;
}
}
用法:
List<MyEntity> list1 = new List<MyEntity>();
List<MyEntity> list2 = new List<MyEntity>();
List<MyEntity> addedList = new List<MyEntity>();
list1.Add(new MyEntity()
{
Name = "A",
Value = 1
});
list1.Add(new MyEntity()
{
Name = "B",
Value = 1
});
list2.Add(new MyEntity()
{
Name = "A",
Value = 2
});
addedList = list1.AddList(list2);
问候
好的,我想出了第二个解决方案。看,我不是 lambda 专家,所以我只是觉得这太棒了!
public static class MyEntityListExtension
{
public static List<MyEntity> AddList(this List<MyEntity> FirstList, List<MyEntity> SecondList)
{
return FirstList.Join<MyEntity, MyEntity, string, MyEntity>(SecondList, x => x.Name, y => y.Name, (x, y) =>
{
return new MyEntity()
{
Name = x.Name,
Value = x.Value + y.Value
};
}).ToList<MyEntity>();
}
}