基于三个不同的字段返回非独特对象

时间:2013-01-03 23:25:09

标签: c# .net linq

鉴于以下内容,我希望能够基于两个字段提取非不同的值:名称和国家/地区。在这个例子中,我想要返回列表中的前两个。

List<City> cities = new List<City>
{
new City{ Name = "Sydney", Country = "Australia", Galaxy = "Mine"  },
new City{ Name = "Sydney", Country = "Australia", Galaxy = "Yours" },
new City{ Name = "New York", Country = "USA", Galaxy = "Ours"},
new City{ Name = "Paris", Country = "France", Galaxy = "Theirs" },

};

1 个答案:

答案 0 :(得分:3)

此查询将按名称和国家/地区返回非不同城市(即您的情况中的前两个):

IEnumerable<City> query = 
    cities.GroupBy(c => new { c.Name, c.Country })
          .Where(g => g.Count() > 1)
          .SelectMany(g => g);