运用Linq,将List<T> 转换为 Dictionary<T Key,T Value>
即:List<T> ToDictionary<T Key,T Value>
废话不说,看代码:
示例代码:按照性别分类
class Program
{
public class Student
{
public string Name { get; set; }
public int Age { get; set; }
public int Sex { get; set; }
} static void Main(string[] args)
{
List<Student> lstStudent = new List<Student>();
lstStudent.Add(new Student { Name = "A1", Age = , Sex = });
lstStudent.Add(new Student { Name = "A2", Age = , Sex = });
lstStudent.Add(new Student { Name = "A3", Age = , Sex = });
lstStudent.Add(new Student { Name = "A4", Age = , Sex = });
lstStudent.Add(new Student { Name = "A5", Age = , Sex = });
lstStudent.Add(new Student { Name = "A6", Age = , Sex = });
lstStudent.Add(new Student { Name = "A7", Age = , Sex = });
lstStudent.Add(new Student { Name = "A8", Age = , Sex = });
lstStudent.Add(new Student { Name = "A9", Age = , Sex = }); var dicStudent = lstStudent.GroupBy(p => p.Sex).ToDictionary(p => p.Key, p => p.ToList());
foreach (var dic in dicStudent)
{
Console.WriteLine("Key:{0}", dic.Key);
foreach (var stu in dic.Value)
{
Console.WriteLine("Name:{0},Age:{1}", stu.Name, stu.Sex.ToString());
}
}
Console.ReadKey();
}
}
实际运行结果:
Key:
Name:A1,Age:
Name:A4,Age:
Name:A6,Age:
Name:A8,Age:
Name:A9,Age:
Key:
Name:A2,Age:
Name:A3,Age:
Name:A5,Age:
Name:A7,Age:
轻松利用linQ