zoukankan      html  css  js  c++  java
  • 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 { setget; }
            
    public int Num { setget; }
            
    public string Name { setget; }
        }
    }

    如果用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();
    }
    自:http://www.cnblogs.com/yjmyzz/archive/2009/12/04/1617240.html
  • 相关阅读:
    SpringMVC 拦截器不拦截静态资源的三种处理方式
    Tomcat启动失败问题 (指定的主资源集 [D:javaapache-tomcat-9.0.35webappsAppManageSystem] 无效)
    oracle转postgresql FOR UPDATE WAIT 5 处理
    jq插件验证
    HTML5数据储存
    canvas 一些 用法大全
    HTML canvas 绘图
    CSS3
    HTML 核心内容
    HTML5 媒体
  • 原文地址:https://www.cnblogs.com/guanjie20/p/1638937.html
Copyright © 2011-2022 走看看