Jer*_*acs 1 c# linq collections generic-programming
假设我有一个相当大的IList<foo>地方,foo看起来像这样:
public class foo
{
public string Region { get; set; }
public string Territory { get; set; }
public string Location { get; set; }
public string Person { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
...是否有一种方法,使用一个相当快速/有效的表达式来"分组"这些foo项目Region,所以我可能最终得到一个IDictionary<string, IList<foo>>并且将string密钥作为Region属性,每个下属IList<foo>只包含与之foo匹配的记录区域?(它不一定是一个IDictionary,只是为了说明我正在尝试做的事情的要点.)我想以这种方式组织我的MVC视图的交互式列表,而不必编写相对复杂的东西或使用第三方库.
是的 - 你想要一个Lookup:
var lookup = list.ToLookup(x => x.Region);
Run Code Online (Sandbox Code Playgroud)
您可以通过分组创建字典,但我个人更喜欢使用查找,因为它是专门为"单键,多值"方案设计的.