c#将新项目附加到列表项目

时间:2015-06-17 22:27:42

标签: c# list

下面的代码中有一行包含两行,我希望能够将这两行合并,并根据国家/地区对收入字段求和。

public class City
{
 public string Name {get;set;}
 public string Country {get;set;}
 public double income {get;set;}
}
public class myClass
{
void Main()
{

 var c = GetCities();
 var d = c.GroupBy(s => new {s.Country, s.Flag, s.Name}).Select(s => new City { Country = s.Key.Country, Flag = s.Key.Flag, Name = s.Key.Name});
 d.Dump(); //LINQPAD output to screen
}

public List<City> GetCities()
{
 List<City> cities = new List<City>();
 cities.Add(new City() { Name = "Istanbul", income= 22.00, Country = "Turkey"  });
 cities.Add(new City() { Name = "", income= 44.88, Country = "Turkey" });
 return cities;
}
}

在我的实际应用程序中,列表是在两个地方生成的,但数据需要显示在一行中。

1 个答案:

答案 0 :(得分:0)

找到了我的答案

var result = c.GroupBy(x => x.Country)
.Select(g => {
var item = g.First();
return new{
Country = item.Country,
Name = item.Name,
income = g.Sum(x => x.income) };
}).ToList();