日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Linq之ToDictionaryTSource, TKey, TElement的写法

發(fā)布時間:2023/11/30 编程问答 39 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。