私は人のリストに人の体重、年齢、都市、名前のプロパティを持っています。Linq抽出法や複数のデータでorder byとgroup byを使うにはどうすればいいですか?
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 = ?????
});
要素:。年齢によってグループ化し、各グループは、最大の重みを選択する必要があります(私がしたいですこのリストは年齢順に並べ替えられますが、リストにはその年齢の最も重い人のみが含まれています)。新しい新しいリストは次のようになります:
(GroupedPersonLiコンテンツ)=>
年齢|重量|名前|市
------- | ------- | ------ | --------
15 | 68 |ダニー|ニューヨーク
17 | 88 |ダニー|ニューヨーク
19 | 75 |ダニー|ニューヨーク
20 | 88 |ダニー|ニューヨーク
foreach (var item in GroupedPersonList)
{
string city = item.City; // Error because No city in list
}
私はこのようにグループ化できます。しかし、私は2つのプロパティ(年齢と体重)しか使用できません。これらのパラメータも割り当てる必要があります。他のパラメータを割り当てる方法は? LINQ抽出法ではどうしたらいいですか?あなたは、私は信じて欲しい
linq関数は、IfやForEachのように、{}でワープすると1行以上のコードを処理できます。 最初に、同じ年齢と場所を持つすべての人の中から最大の体重を持つ人(最初の人はどのように顎の体重を持っていますか)を見出します。 私は年齢(キー)と重量のあるオブジェクトのプロパティを使用して新しいオブジェクトを作成して返します。 –