NET问答: 说说你对 LookupTKey, TElement 的看法 ?
咨詢區(qū)
dan-gph:
MSND 上對(duì) Lookup 做了如下的解釋。
Lookup<TKey, TElement> 類似于 Dictionary<TKey,TValue>, 不同點(diǎn)在于 Dictionary<TKey, TValue> 中的key對(duì)應(yīng)的是單個(gè)value,而 Lookup<TKey, TElement> 中的 key 對(duì)應(yīng)的是一個(gè) value集合。
我覺(jué)得這個(gè)解釋等于沒(méi)解釋,請(qǐng)問(wèn) Lookup 的用途在哪里?
回答區(qū)
bobbymcr:
你可以把 Lookup<TKey, TElement> 和 Dictionary<TKey, Collection<TElement>> 看作是等價(jià)的,很明顯后者通過(guò) key 可以返回與之匹配的 list 集合。
namespace?LookupSample {using?System;using?System.Collections.Generic;using?System.Linq;class?Program{static?void?Main(string[]?args){List<string>?names?=?new?List<string>();names.Add("Smith");names.Add("Stevenson");names.Add("Jones");ILookup<char,?string>?namesByInitial?=?names.ToLookup((n)?=>?n[0]);//?count?the?namesConsole.WriteLine("J's:?{0}",?namesByInitial['J'].Count());?//?1Console.WriteLine("S's:?{0}",?namesByInitial['S'].Count());?//?2Console.WriteLine("Z's:?{0}",?namesByInitial['Z'].Count());?//?0,?does?not?throw}} }點(diǎn)評(píng)區(qū)
相信很多人對(duì) Lookup 不是很理解,我初學(xué)時(shí)也沒(méi)搞特別清楚,真不知道 Lookup 是出自哪里的術(shù)語(yǔ),不過(guò)沒(méi)關(guān)系,沒(méi)聽(tīng)過(guò) Lookup,總聽(tīng)過(guò) GroupBy 吧,對(duì),就是關(guān)系型數(shù)據(jù)庫(kù)中用到的 group by,這兩者是等價(jià)的,只不過(guò)又造了一個(gè)新名詞而已,不信的話,我寫(xiě)個(gè)例子給你看看。
static?void?Main(string[]?args){var?nums?=?new?int[]?{?1,?2,?3,?3?};//使用?lookupILookup<int,?int>?query?=?nums.ToLookup(t?=>?t);foreach?(IGrouping<int,?int>?item?in?query){var?key?=?item.Key;var?list?=?item.ToList();Console.WriteLine($"lookup?:?key={key},?value={string.Join(",",?list)}");}Console.WriteLine($"\r\n??--------------?\r\n");//使用?groupIEnumerable<IGrouping<int,?int>>?query2?=?nums.GroupBy(t?=>?t);foreach?(IGrouping<int,?int>?item?in?query2){var?key?=?item.Key;var?list?=?item.ToList();Console.WriteLine($"groupby?:?key={key},?value={string.Join(",",?list)}");}Console.ReadLine();}從結(jié)果看,兩者都做了相同的事情,仔細(xì)觀察代碼,你會(huì)發(fā)現(xiàn)在 foreach 的迭代項(xiàng) item 都是 IGrouping<int, int> 類型,接下來(lái)就有一個(gè)疑問(wèn)了,query 還能被 foreach 嗎?這個(gè)要看 ILookup<int, int> 的內(nèi)部迭代類是怎么寫(xiě)的了,翻一下代碼看看。
public?class?Lookup<TKey,?TElement>?:?IEnumerable<IGrouping<TKey,?TElement>>,?IEnumerable,?ILookup<TKey,?TElement> {public?IEnumerator<IGrouping<TKey,?TElement>>?GetEnumerator(){Grouping?g?=?lastGrouping;if?(g?!=?null){do{g?=?g.next;yield?return?g;}while?(g?!=?lastGrouping);}} }看到?jīng)]有,迭代類返回的類型 IEnumerator<IGrouping<TKey, TElement>> 不正是做 GroupBy 的 query2 類型 IEnumerable<IGrouping<int, int>> 嘛 ~~~
如果你要不懂 sql 的 group by, 那就當(dāng)我沒(méi)說(shuō)哈 ????????????
原文鏈接:https://stackoverflow.com/questions/1403493/what-is-the-point-of-lookuptkey-telement
總結(jié)
以上是生活随笔為你收集整理的NET问答: 说说你对 LookupTKey, TElement 的看法 ?的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: [C#.NET 拾遗补漏]16:几个常见
- 下一篇: NET问答:什么场景下应该选择 stru