Linq之ToDictionaryTSource, TKey, TElement的写法
生活随笔
收集整理的這篇文章主要介紹了
Linq之ToDictionaryTSource, TKey, TElement的写法
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
以前一直用 var query = xxx.Select(c=>new {c.X,c.Y}); 來取表中的某二列字段,今天有個應(yīng)用需要轉(zhuǎn)成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)); //如果覺得上面的寫法太復(fù)雜,還可以簡化為 //?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反射一下,會發(fā)現(xiàn)實際上編譯器自動生成了類似以下代碼:(部分名稱做了友好處理)?
代碼 [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:今天寫的好象都是些水文 :)
轉(zhuǎn)載于:https://www.cnblogs.com/yjmyzz/archive/2009/12/04/1617240.html
總結(jié)
以上是生活随笔為你收集整理的Linq之ToDictionaryTSource, TKey, TElement的写法的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: vml的简易画板_2
- 下一篇: IE8无法调试?IE进入不了调试状态