简体   繁体   中英

Grouping Key Value pairs with Linq and List

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

            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?

您可以编写_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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM