NET问答: 说说你对 LookupTKey, TElement 的看法 ?
咨詢區
dan-gph:
MSND 上對 Lookup 做了如下的解釋。
Lookup<TKey, TElement> 類似于 Dictionary<TKey,TValue>, 不同點在于 Dictionary<TKey, TValue> 中的key對應的是單個value,而 Lookup<TKey, TElement> 中的 key 對應的是一個 value集合。
我覺得這個解釋等于沒解釋,請問 Lookup 的用途在哪里?
回答區
bobbymcr:
你可以把 Lookup<TKey, TElement> 和 Dictionary<TKey, Collection<TElement>> 看作是等價的,很明顯后者通過 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}} }點評區
相信很多人對 Lookup 不是很理解,我初學時也沒搞特別清楚,真不知道 Lookup 是出自哪里的術語,不過沒關系,沒聽過 Lookup,總聽過 GroupBy 吧,對,就是關系型數據庫中用到的 group by,這兩者是等價的,只不過又造了一個新名詞而已,不信的話,我寫個例子給你看看。
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();}從結果看,兩者都做了相同的事情,仔細觀察代碼,你會發現在 foreach 的迭代項 item 都是 IGrouping<int, int> 類型,接下來就有一個疑問了,query 還能被 foreach 嗎?這個要看 ILookup<int, int> 的內部迭代類是怎么寫的了,翻一下代碼看看。
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);}} }看到沒有,迭代類返回的類型 IEnumerator<IGrouping<TKey, TElement>> 不正是做 GroupBy 的 query2 類型 IEnumerable<IGrouping<int, int>> 嘛 ~~~
如果你要不懂 sql 的 group by, 那就當我沒說哈 ????????????
原文鏈接:https://stackoverflow.com/questions/1403493/what-is-the-point-of-lookuptkey-telement
總結
以上是生活随笔為你收集整理的NET问答: 说说你对 LookupTKey, TElement 的看法 ?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [C#.NET 拾遗补漏]16:几个常见
- 下一篇: 4月 .NET 线上 Meetup,快