代码改变世界

ToLookup方法

2022-01-25 23:33  hello,逗比  阅读(539)  评论(0编辑  收藏  举报

1、必须是实现了IEnumerable接口对象才可以调用该方法,通过ToLookup方法,返回的是ILookup<T1,KeyValuePair<T2,T3>>  对象,

筛选KeyValuePair<T2,T3>集合里符合条件的新的数据,并且生成新的集合以类型T1为key,KeyValuePair<T2,T3> 为值。

访问这个这个值是可以用索引访问 lookup[“T1”],访问key可以遍历元素时候,用 元素的key来访问。

另外:ILookup<Tkey,Telement> ,是一个key可以对应多个内容的。

如下例子


 Dictionary<string, string> dic = new Dictionary<string, string>();
            dic.Add("1", "a");
            dic.Add("2", "b");
            dic.Add("3", "c");
            dic.Add("4", "a");
            ILookup<string,KeyValuePair<string,string>> lookups = dic.ToLookup(a => a.Value);
            foreach(var i in lookups["a"])
                Console.WriteLine(i);
            foreach(var i in lookups)
            {
                Console.WriteLine(i.Key);
            }


            List<person> list = new List<person>() { new person("a",1),new person("b",2),new person("c",3)};
             ILookup<int,person> ilookup = list.ToLookup(a => (a.name == "a" || a.name == "b") ? a.age : -1);
            foreach(var item in ilookup)
            {
                Console.WriteLine(item.Key );
                Console.WriteLine(ilookup[item.Key]);
                  foreach(var item1 in ilookup[item.Key])
                 {
                      Console.WriteLine(item1.name);
                 }
            }
            foreach (person item in ilookup[1])
            {
                Console.WriteLine(item.name);
                // Console.WriteLine(ilookup[item]);
            }