使用Linq和List对键值对进行分组

时间:2011-06-22 16:14:06

标签: c# linq 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();
        }
    } 

这构建列表并对它们进行分组,我可以得到每个对象的计数,我只是无法获得值。我似乎只能得到钥匙。

我确信有一百万种方法可以做到这一点,我真的想选择一个我理解的方法。好吧,我想我只是不理解它。

我应该返回并使用查找从_popularNotes列表中获取名称吗?或者是否有另一种方法来实际构建和输出带有键/值对加上计数的列表?

2 个答案:

答案 0 :(得分:2)

您可以撰写_noteGroup.First()

答案 1 :(得分:1)

IGrouping<TKey, TElement>IEnumerable<TElement>,这意味着您可以对其进行枚举。

根据the documentation of 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);
}