如何比较基于常见字符串值的两个列表?
问题描述:
我有对象的两个列表集合在一个格式:如何比较基于常见字符串值的两个列表?
list1{
new Object1{ State= "AL" , Value = 3.123}
new Object2{ State= "CO", Value = 2.111}
}
list2{
new Object1{State="AL", Value=2.123}
new Object2{State="CO", Value=3.111}
}
我需要比较这两个列表,并产生另一个列表如下所示:
list3{
new Object1{State="AL", Value= (3.123 + 2.123)}
new Object2{ State="CO", Value =(2.111 + 3.111) }
}
有人可以告诉我,我该怎么做这个?
答
安德烈的答案肯定会奏效。你可以概括这分组的概念,并支持IEnumerables
任意数量的合并
List<MyEntity> source1 = ...;
List<MyEntity> source2 = ...;
IEnumerable<MyEntity> source3 = ...;
var mergedList = (from item in source1.Contact(source2).Concat(source3)
group item by item.Name into g
select new MyEntity { Name = g.Key, Value = g.Sum(e => e.Value) })
.ToList();
+0
我刚刚用完整的lambda选项编辑了我的答案,但是这个LINQ选项也非常好。 +1 – 2012-07-31 05:24:36
答
检查了这一点:
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);
问候
好球员,我想出了这个第二个解决方案。看,我不是拉姆达专家,所以我只是觉得这太棒了!
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>();
}
}
答
我没有测试的代码,但是这可能给你一些想法....
List<Obj> list1= New List(obj1,obj2);
List<Obj> list2= New List(obj3,obj4);
var allObjects=
from list1.Concat(list2);
var list3=from o in allObjects
group o by o.State into g
select new {State=g.key,Value=g.Sum(p => p.Value)};
foreach (var obj in list3)
{
Console.WriteLine("{0},{1}",obj.State,obj.Value);
}
我不是LINQ专家,但是你的代码示例似乎不是有效的C#语法?!? – 2012-07-31 05:02:43
是的,这不是有效的C#语法。这只是为了解释我的问题。 – NewBie 2012-07-31 05:03:56