簡體   English   中英

用Linq和List分組鍵值對

[英]Grouping Key Value pairs with Linq and List

我正在嘗試獲取一長串項,一個鍵/值對,並按鍵對它們進行分組。 這樣做,我想獲得每個鍵/值對的計數,以便稍后可以獲取加權列表。 我用於生成列表的代碼與此示例類似:

class Notes
    {
        public int NoteId { get; set; }
        public string NoteName { get; set; }
    }
    class Program
    {
        static void Main(string[] args)
        {
            List<Notes> _popularNotes = new List<Notes> { 
              new Notes { NoteId = 1, NoteName = "Title 1" }, 
          new Notes { NoteId = 1, NoteName = "Title 1" },
          new Notes { NoteId = 2, NoteName = "Title 2" },
          new Notes { NoteId = 4, NoteName = "Title 4" },
          new Notes { NoteId = 4, NoteName = "Title 4" } };

            foreach (var _note in _popularNotes)
                Console.WriteLine(_note.NoteId + ": " + _note.NoteName);

            IEnumerable<IGrouping<int, string>> _query = _popularNotes.GroupBy(x => x.NoteId, x => x.NoteName);

            foreach (var _noteGroup in _query)
            {
                Console.WriteLine(_noteGroup.Key + ": " + _noteGroup.Count());
            }

            Console.ReadKey();
        }
    } 

這將建立列表並將它們分組,我可以獲取每個對象的數量,而我無法獲取值。 我似乎只能拿到鑰匙。

我敢肯定,有100萬種方法可以做到這一點,我實際上是在嘗試選擇我了解的方法。 我想我只是不理解它。

因此,我應該返回並通過_popularNotes列表獲取名稱嗎? 還是有另一種方法來實際構建和輸出鍵/值對加上計數的列表?

您可以編寫_noteGroup.First()

IGrouping<TKey, TElement>IEnumerable<TElement> ,這意味着您可以對其進行枚舉。

根據IGrouping<TKey, TElement>的文檔

public interface IGrouping<out TKey, out TElement> : IEnumerable<TElement>,
    IEnumerable

換句話說,要吐出鍵+計數,然后吐出該組中的所有元素(在您的情況下為名稱),您可以執行以下操作:

foreach (var _noteGroup in _query)
{
    Console.WriteLine(_noteGroup.Key + ": " + _noteGroup.Count());
    foreach (var name in _noteGroup)
        Console.WriteLine("   " + name);
}

暫無
暫無

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

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