前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Linq之ToDictionary<TSource, TKey, TElement>的写法

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

作者头像
菩提树下的杨过
发布2018-01-23 12:00:27
6060
发布2018-01-23 12:00:27
举报
文章被收录于专栏:菩提树下的杨过

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

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

代码语言:js
复制
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反射一下,会发现实际上编译器自动生成了类似以下代码:(部分名称做了友好处理) 

代码语言:js
复制
[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:今天写的好象都是些水文 :)

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2009-12-04 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档