我有一个人名单,其中包含人的体重,年龄,城市和姓名属性。
Person.cs:
public class Person
{
public int Weight { get; set; }
public int Age { get; set; }
public string Name {get; set;}
public string City {get; set;}
}
的Program.cs:
List<Person> personList = new List<Person>();
personList.Add(new Person { Age = 15, Weight = 68, Name = “Dany”, City =”New York” });
personList.Add(new Person { Age = 19, Weight = 75, Name = “Dany”, City =”New York” });
personList.Add(new Person { Age = 17, Weight = 68, Name = “Dany”, City =”New York” });
personList.Add(new Person { Age = 15, Weight = 55, Name = “Dany”, City =”New York” });
personList.Add(new Person { Age = 15, Weight = 53, Name = “Dany”, City =”New York” });
personList.Add(new Person { Age = 17, Weight = 88, Name = “Dany”, City =”New York” });
personList.Add(new Person { Age = 19, Weight = 45, Name = “Dany”, City =”New York” });
personList.Add(new Person { Age = 20, Weight = 88, Name = “Dany”, City =”New York” });
//Grouped person list
List<People> GroupedPersonList = new List<People>();
var GroupedPersonList = personList.GroupBy(x => x.Age , (key,element) => new
{
Age = key,
Weight = element.Max(c=>c.Weight)
City = ????,
Name = ?????
});
应列出的元素:按年龄分组,每组应选择最高权重。(我想按年龄排序此列表,但列表中只包含该年龄段最重的人。然后我将创建一个通过这个新列表。)新的新列表应如下所示:
(GroupedPersonList Contents)=&gt;
年龄|重量|名称|城市
------- | ------- | ------ | --------
15 | 68 | Dany |纽约
17 | 88 | Dany |纽约
19 | 75 | Dany |纽约
20 | 88 | Dany |纽约
foreach (var item in GroupedPersonList)
{
string city = item.City; // Error because No city in list
}
我可以这样分组。但我只能使用2个属性(年龄和重量)。我还需要分配这些参数。如何分配其他参数?我怎么能在LINQ提取方法中做到这一点?
答案 0 :(得分:3)
你想要的我相信是这样的:
var GroupedPersonList = personList
.OrderByDescending(x => x.Weight)
.GroupBy(x=>x.Age)
.Select(x =>x.First())
.OrderBy (x => x.Age);
这样做需要原始列表和:
这假定GroupedPersonList
应该是List<Person>
,尽管您确实引用它是List<People>
,所以我可能误解了某些内容。如果People
确实是一个对象,那么请告诉我们它的样子!
此外,您的最终列表将引用与原始列表相同的对象,因此如果您对这些对象进行了更改,则会反映在原始对象中。这可能是也可能不是你想要的。但它确实意味着您可以访问Person对象上的每个属性,而无需像在您的代码中那样单独设置它们。
答案 1 :(得分:2)
var GroupedPersonList = personList.GroupBy(x => x.Age, (key, element) =>
{
var weightiest = element.First(p => p.Weight == element.Max(c => c.Weight));
return new
{
Age = key,
Weight = weightiest.Weight,
City = weightiest.City,
Name = weightiest.Name
};
});
答案 2 :(得分:2)
var GroupedPersonList = personList.GroupBy(
x => x.Age,
(k, x) => x.OrderByDescending(p => p.Weight).First());