日期:2014-05-18  浏览次数:20872 次

list 求合并相同元素的值
a 3
b 5
c 9
d 1
b 7

上边中有相同的b,合并后效果
a 3
b 12
c 9
d 1

  /*List<DataClass.jx_so> listk = new List<DataClass.jx_so>();

  List<string> listL = new List<string>();
  List<string> listL2 = new List<string>();
  for (int k = 0; k < listk.Count; k++)
  {
  //if (listL.IndexOf(listk[k]) == -1)
  // listL.Add();
  }
*/

求高人帮忙解决一下!



------解决方案--------------------
C# code
List<DataClass.jx_so> listk = new List<DataClass.jx_so>()
{
    new DataClass.jx_so() { x = "a", y = 3 }, //假设a 3两个值装在x y两个成员里
    new DataClass.jx_so() { x = "b", y = 5 },
    ...
};
var result = from j in listk
             group j by j.x into g
             select new DataClass.jx_so() { x = g.Key, y = g.Sum(z => z.y) };