Site icon Amelt.net

C#:Group duplicate elements of List to Dictionary Key

Amelt

Amelt

This post is also available in: 日本語 (Japanese)

This article is about How to use C# to group duplicate elements in List type into Dictionary Key and extract the value .
I think that this article is most suitable for those who say "Linq's Groupby can be used to write beautiful code, but I'd like to put a duplicate grouped value on the console for the time being!"

Group duplicate elements in List into Dictionary Key

Sample code to group duplicate elements using Linq, by use C# console application generated by VisualStudio as an example.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SampleConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            //Result type list creation, with duplicate elements
            List<Result> data = new List<Result>();
            //Add data
            data.Add(new Result(0, "Tan", "Osaka"));
            data.Add(new Result(1, "Suzu", "Osaka"));
            data.Add(new Result(2, "Tan", "Nagoya"));
            data.Add(new Result(3, "Suzu", "Tokyo"));
            data.Add(new Result(4, "Suzu", "Osaka"));
            //Grouping addresses with Linq at the same time as creating a dictionary type
            Dictionary<string, List<Result>> dict = data
            .ToLookup(Result => Result.address)
            .ToDictionary(
            g => g.Key,
            g => g.ToList()
            );
            //Create an array to store the dict
            string[] values = new string[dict.Count];
            //Copy the Key of dict
            dict.Keys.CopyTo(values, 0);
            //Sort copied keys
            Array.Sort(values);
            //Extract the contents of values
            for (int i = 0; i < dict.Count; i++)
            {
                Console.WriteLine("---values[i]---");
                Console.WriteLine(values[i]);
                Console.WriteLine("---dict[\"Osaka\"][i].name---");
                Console.WriteLine(dict["Osaka"][i].name);
            }
            Console.ReadKey();
        }

        // Class List<Result> 
        public class Result
        {
            public int id;
            public string name;
            public string address;
            public Result(int _id, string _name, string _address)
            {
                id = _id; name = _name; address = _address;
            }
        }

    }
}

Specify the key you want to group using Linq, like "ToLookup(Result => Result.address)".
In the above example, I think there is a better way, but the list "Osaka" is treated as a duplicate element and grouped into a Dictionary type Key.

Next, copy the Dictionary type Key to the array in dict.Keys.CopyTo().
The reason for copying is that the order becomes random in the case of Dictionary type, so it is copied to the array and sorted, and the desired value is taken out in the for loop.

To extract the value corresponding to the dictionary key, you can extract it with dict["Osaka"][i].name .

Console.WriteLine("---values[i]---");
Console.WriteLine(values[i]);
//////////Result of for loop
---values[i]---
Osaka
---values[i]---
Tokyo
---values[i]---
Nagoya
Console.WriteLine("---dict[\"Osaka\"][i].name---");
Console.WriteLine(dict["Osaka"][i].name);
//////////Result of for loop
---dict["Osaka"][i].name---
Tan
---dict["Osaka"][i].name---
Suzu
---dict["Osaka"][i].name---
Suzu
No tags for this post.