C#探秘系列(一)——ToDictionary,ToLookup
概述
ToDictionary和ToLookup都是基于IEnumerable
ToDictionary
描述
ToDictionary将IEnumerable中的元素转换为一个新的Dictionary
语法
public static Dictionary<TKey, TElement> ToDictionary<TSource, TKey, TElement>(
this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector,
Func<TSource, TElement> elementSelector
)
示例
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
List<Person> persons = new List<Person>()
{
new Person() { Id = 1, Name = "张三" },
new Person() { Id = 2, Name = "李四" },
new Person() { Id = 3, Name = "王五" },
};
Dictionary<int, string> personDict =
persons.ToDictionary(p => p.Id, p => p.Name);
foreach (KeyValuePair<int, string> kvp in personDict)
{
Console.WriteLine("Key: {0}, Value: {1}", kvp.Key, kvp.Value);
}
}
}
class Person
{
public int Id { get; set; }
public string Name { get; set; }
}
输出结果:
Key: 1, Value: 张三
Key: 2, Value: 李四
Key: 3, Value: 王五
ToLookup
描述
ToLookup将IEnumerable中的元素转换为一个新的ILookup
语法
public static ILookup<TKey, TElement> ToLookup<TSource, TKey, TElement>(
this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector,
Func<TSource, TElement> elementSelector
)
示例
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
List<Person> persons = new List<Person>()
{
new Person() { Id = 1, Name = "张三" },
new Person() { Id = 2, Name = "李四" },
new Person() { Id = 3, Name = "张三" },
};
ILookup<string, Person> personLookup =
persons.ToLookup(p => p.Name, p => p);
foreach (Person p in personLookup["张三"])
{
Console.WriteLine(p.Id);
}
}
}
class Person
{
public int Id { get; set; }
public string Name { get; set; }
}
输出结果:
1
3
总结
ToDictionary和ToLookup都是非常常用的方法,利用它们可以将IEnumerable中的数据转换为Dictionary或ILookup,方便操作和使用。要注意的是,ToLookup返回的是ILookup而不是Dictionary,ILookup可以包含重复的键,而Dictionary不行。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:C#探秘系列(一)——ToDictionary,ToLookup - Python技术站