首页 > 代码库 > List分组后存入Dictionary

List分组后存入Dictionary

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

namespace lambdaTest
{
    class Program
    {
        static void Main(string[] args)
        {
            List<user> userset = new List<user>();
            for (int i = 0; i < 10; i++)
            {
                user u = new user();
                u.name = i.ToString() + "的名字";
                u.age = i;
                u.sex = (i % 2 == 0) ? "男" : "女";
                userset.Add(u);
            }
            var query = userset.GroupBy(m => m.sex).ToList().ToDictionary(n=>n.Key);
            Dictionary<string, IGrouping<string, user>> d = new Dictionary<string, IGrouping<string, user>>();
            foreach (var item in query)
            {
                d.Add(item.Key,item.Value);
            }
            foreach (var item in d)
            {
                foreach (var i in item.Value)
                {
                    Console.WriteLine(item.Key + " "+i.name);
                }
            }
           
            Console.ReadKey();
        }
    }
    public class user
    {
        public string name;
        public string sex;
        public int age;
    }
}

  结果:技术分享

 

List分组后存入Dictionary