簡體   English   中英

從linq查詢中獲取對象列表

[英]Get list of list of objects from linq query

有什么方法可以查詢對象列表,對其進行分組,然后將它們作為自己的列表輸出為列表列表? 我不知道該怎么解釋,所以我會告訴你。

public class Note
{
    string CreatorID;
    string Title;
    string Text;
}

我有一個填充的筆記List<Note> noteListList<Note> noteList )。 有多個創作者,每個創作者都有多個注釋。 我試圖找出是否有一種使用LINQ查詢按CreatorID將注釋分組的方法,然后將它們分開並輸出為注釋List<List<Note>> creatorsNotesList<List<Note>> creatorsNotes )。 這樣,我可以遍歷creatorsNotes以獲取創建者及其注釋列表。

最簡單的方法是使用ToLookup

var groups = noteList.ToLookup(n => n.CreatorID);

foreach(var group in groups)
{
    Console.WriteLine("Items with CreatorID {0}", group.Key);
    foreach(var item in group)
          Console.WriteLine("   Title: {0}", item.Title);
}

如果需要,您也可以使用GroupBy 請注意,這些不會直接創建List<List<Note>> 如果需要,您可以執行以下操作:

List<List<Note>> grouped = noteList.GroupBy(n => n.CreatorID)
                                   .Select(g => g.ToList()) 
                                   .ToList();

當然,讓listList<Note>

var creatorNotes = list
    .GroupBy(note => note.CreatorID)
    .Select(g => new
    {
        g.CreatorID,
        Notes = g.ToList()
    })
    .ToList();

正如Reed所指出的,這是一個匿名類型的列表,該列表指示根目錄中的分組的CreatorID以及與該CreatorID關聯的Notes

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM