我有一個學生類如下:
public class Student
{
public string Name { get; set; }
public int? Age { get; set; }
public bool? IsMale { get; set; }
}
并具有將學生分配為字典的課程串列,其中所有課程都存盤為:
Dictionary<string, List<Student>>
其中 Key ( string ) 是課程代碼,Value ( List< student > ) 是注冊到該特定課程且所有屬性都有值的學生。
現在我只想用學生的名字來簡化資料集。所以我仍然會有一個Dictionary<string, List<Student>>只Name為每個Student物件設定屬性的地方。
我如何撰寫這樣的 LINQ 查詢來根據需要獲取資料?
uj5u.com熱心網友回復:
由于字典實作IEnumerable<KeyValuePair<string, List<Student>>>,您可以撰寫
var newDict = oldDict
.ToDictionary(
kvp => kvp.Key,
kvp => kvp.Value.Select(s => new Student { Name = s.Name }).ToList()
);
請注意,我們有一個基于學生串列的嵌套 LINQ 查詢。它選擇串列中的所有學生并創建新學生,僅將名稱設定到新串列中。
因此,對于每個 KeyValuePair,我們保留 Key(課程代碼),但創建一個新的 Value 作為簡化的學生串列。
相反,您還可以創建一個Dictionary<string, List<string>>with
var newDict = oldDict
.ToDictionary(
kvp => kvp.Key,
kvp => kvp.Value.Select(s => s.Name).ToList()
);
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/360043.html
