我正在使用带有SQL Server数据库的Entity Framework MVC应用程序。
我在表中有一个dict(string,string of list)类型的字典结构,类似:
var dict = { "Apple",["Red","Blue","Green"],
"Orange",["Orange","Pink","Lavender"]
"Mango",["Yellow","Brown","Indigo"]
}
我还有另一种颜色列表[红色,蓝色,粉红色]。
var lstColors = ["Red","Blue","Pink"]
像下面这样从第一个列表中仅创建第二个列表中的结构的最有效方法是什么。
var finalDict = {
"Apple",["Red","Blue"],
"Orange",["Pink"]
}
答案 0 :(得分:2)
很难理解您的伪代码,但是您需要这样做:
List<string> colorList = new List<string>{"Red","Blue","Pink"};
Dictionary<string, List<string>> finalDict = dict
.Select(kv => new
{
Fruit = kv.Key,
MatchingColors = kv.Value.Intersect(colorList).ToList()
})
.Where(x => x.MatchingColors.Any())
.ToDictionary(x => x.Fruit, x => x.MatchingColors);
所有集合都在内存中,因此这是LINQ-To-Objects,与实体框架无关。