using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ToLookupDemo
{
class Program
{
//自定义类
public class Product
{
public string Code { get; set; }
public string Description { get; set; }
}
static void Main(string[] args)
{
List<Product> products = new List<Product>
{
new Product{Code="SPM1",Description="1"},
new Product{Code="LME1",Description="3"},
new Product{Code="SUP1",Description="4"},
new Product{Code="SPM2",Description="2"},
new Product{Code="SUP2",Description="5"}
};
//转换为Lookup类型,得到的结果已经分组了
Lookup<string, string> lookup = (Lookup<string, string>)
products.ToLookup(c => c.Code.Substring(0, 3), c => c.Code + " " + c.Description);
//在结果中循环
foreach (IGrouping<string, string> group in lookup)
{
Console.WriteLine(group.Key);
foreach (string s in group)
Console.WriteLine(" {0}", s);
}
Console.ReadLine();
//取得其中一组值
IEnumerable<string> spmGroup = lookup["SPM"];
foreach (var str in spmGroup)
Console.WriteLine(str);
Console.ReadLine();
}
}
}