开发者

Grouping Key Value pairs with Linq and List

开发者 https://www.devze.com 2023-03-14 13:53 出处:网络
I\'m trying to take a long list of items, a key/value pair, and group them by key. Doing this I want to get the count of each key/value pair so I can for a weighted list later on. The code I have for

I'm trying to take a long list of items, a key/value pair, and group them by key. Doing this I want to get the count of each key/value pair so I can for a weighted list later on. The code I have for generating the list is similar to this sample:

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" } };

           开发者_JAVA百科 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();
        }
    } 

This build the list and groups them and I can get the count of each object, I just cant get the value. I can only seem to get just the key.

With I'm sure a million ways to do this I'm really trying to pick one I understand. And well I'm just not understanding it I guess.

So should I go back and get the name from the _popularNotes list with a lookup? Or is there another way of actually building and outputting the list with the key/value pair plus the count?


You can write _noteGroup.First()


IGrouping<TKey, TElement> is an IEnumerable<TElement> which means you can enumerate over it.

As per the documentation of IGrouping<TKey, TElement>:

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

In other words, to spit out the key + count, and then all the elements (names in your case) in that group, you can do:

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

精彩评论

暂无评论...
验证码 换一张
取 消