C# 配列やリストのグループ化を行う

  • 作成日 2021.10.21
  • 更新日 2022.04.02
  • C#
C# 配列やリストのグループ化を行う

C#で、配列やリストのグループ化を行うサンプルコードを記述してます。

環境

  • OS windows10 pro 64bit
  • Microsoft Visual Studio Community 2019 Version 16.7.1

グループ化を行う

グループ化を行うには、Linqの「GroupBy」を使用します。

以下は、プロパティ「Id」によりグループ化を行ったコードとなります。

using System;
using System.Collections.Generic;
using System.Linq;

namespace testapp
{

    internal class sample
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Score { get; set; }
    }
    class Program
    {

        private static List<sample> samples = new List<sample>() {
                new sample() { Id = 2, Name = @"b", Score = 20 },
                new sample() { Id = 1, Name = @"a", Score = 50 },
                new sample() { Id = 2, Name = @"a", Score = 20 },
                new sample() { Id = 2, Name = @"b", Score = 20 },
                new sample() { Id = 3, Name = @"c", Score = 50 },
                new sample() { Id = 2, Name = @"a", Score = 20 },
        };

        static void Main(string[] args)
        {

            try
            {
                IEnumerable<IGrouping<int, sample>> reault = samples.GroupBy(v => v.Id);

                foreach (var group in reault)
                {
                    Console.WriteLine("キー : {0}", group.Key);
                    var item = group.ToList();
                    for (int i = 0; i < item.Count; i++)
                    {
                        Console.WriteLine("[{0}] id = {1}, Name = {2}, Score = {3}", i, item[i].Id, item[i].Name, item[i].Score);
                    }
                }

            }
            catch (Exception e)
            {
                System.Console.WriteLine(e.ToString());
            }
        }
    }
}

実行結果