Linq之ToDictionary<TSource, TKey, TElement>的写法

时间:2022-04-23
本文章向大家介绍Linq之ToDictionary<TSource, TKey, TElement>的写法,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

以前一直用 var query = xxx.Select(c=>new {c.X,c.Y}); 来取表中的某二列字段,今天有个应用需要转成Dictionary<T,U>,很少这样使用,居然忘记了写法!

回忆了半天终于写对了,贴在这里备个份,方便以后查找:

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

namespace DicTest
{
 class Program
    {
 static void Main(string[] args)
        {
            List<Test> lst = new List<Test>();
 for (int i = 0; i < 10; i++)
            {
                lst.Add(new Test() { Id = Guid.NewGuid(), Num = i, Name = i.ToString() });
            }

 Dictionary<Guid, int> dic = lst.ToDictionary(new Func<Test, Guid>(c => c.Id), new Func<Test, int>(c => c.Num));
 
 //如果觉得上面的写法太复杂,还可以简化为
 // Dictionary<Guid, int> dic = lst.ToDictionary(c => c.Id, c => c.Num); 

 foreach (Guid Id in dic.Keys)
            {
                Console.WriteLine("Key:{0}tValue:{1}", Id, dic[Id]);
            }

            Console.Read();
        }
    }


 public class Test
    {
 public Guid Id { set; get; }
 public int Num { set; get; }
 public string Name { set; get; }
    }
}

如果用Reflector反射一下,会发现实际上编译器自动生成了类似以下代码:(部分名称做了友好处理) 

[CompilerGenerated]
private static Func<Test, Guid> funcGuid;
 
[CompilerGenerated]
private static Func<Test, int> funcInt;
 
[CompilerGenerated]
private static int mNum(Test c)
{
 return c.Num;
}
 
[CompilerGenerated]
private static Guid mId(Test c)
{
 return c.Id;
}


private static void Main(string[] args)
{
    List<Test> lst = new List<Test>();
 for (int i = 0; i < 10; i++)
    {
        Test _t = new Test();
        _t.Id = Guid.NewGuid();
        _t.Num = i;
        _t.Name = i.ToString();
        lst.Add(_t);
    }
    Dictionary<Guid, int> dic = lst.ToDictionary<Test, Guid, int>((funcGuid != null) ? funcGuid : (funcGuid = new Func<Test, Guid>(Program.mId)), (funcInt != null) ? funcInt : (funcInt = new Func<Test, int>(Program.mNum)));
 foreach (Guid Id in dic.Keys)
    {
        Console.WriteLine("Key:{0}tValue:{1}", Id, dic[Id]);
    }
    Console.Read();
}

PS:今天写的好象都是些水文 :)