我有一个列表字典,并想知道是否有一种获得所有常用值的好方法。例如:
Dictionary<int, List<string>> myDictionary = new Dictionary<int, List<string>>();
并且在其中我说了4个键,每个键都有一个列表,我想获得字典中包含'Oscar','Pablo','John'的所有值。
注意:我不知道我在寻找什么,我只是得到这本字典,需要找到所有三个列表中的所有名称。
返回示例:
说我有一本带
的字典Key=1 Value = List with {'Oscar', 'John','Pablo','Pedro'}
Key=2 Value = List with {'Duvan','Samuel','Pablo','Pedro'}
Key=3 Value = List with {'Camilo','Pablo','Julian'}
Return a list of List with {'Pablo'}
任何帮助都将不胜感激。
答案 0 :(得分:2)
首先从列表中收集所有名称:
var allNames = dict.SelectMany(p => p.Value).Distinct().ToList();
现在您可以按如下方式过滤此列表:
var res = allNames
.Where(s => dict.Count(p => p.Value.Contains(s)) == dict.Count)
.ToList();
答案 1 :(得分:1)
我会这样看:
var myDictionary = new Dictionary<int, List<string>>()
{
{ 1, new List<string>() { "Oscar", "Pablo", "John" } },
{ 2, new List<string>() { "Foo", "Hello", "World" } },
};
var names = new HashSet<string>() { "John", "Oscar", "Pablo"};
var matchesAll = myDictionary.Values.Where(v => names.All(n => v.Contains(n)));
var matchesAny = myDictionary.Values.Where(v => names.Any(n => v.Contains(n)));
最后两个选择取决于您是否希望所有单词匹配或任何单词。
根据您的评论,如果您想要所有字典值中常见的名称列表,那么您可以这样做:
var myDictionary = new Dictionary<int, List<string>>()
{
{ 1, new List<string>() { "Oscar", "Pablo", "John" } },
{ 2, new List<string>() { "Foo", "John", "World" } },
};
var commonInAll = myDictionary.Values.Aggregate((x, y) => x.Intersect(y).ToList());
在这种情况下,您只会在最终{ "John" }
列表中获得commonInAll
。
答案 2 :(得分:0)
你可以试试这个:
Dictionary<int, List<string>> myDictionary = new Dictionary<int, List<string>>();
myDictionary.Add(1, new List<string>()
{
"Oscar", "Pablo", "John"
});
myDictionary.Add(2, new List<string>()
{
"Foo", "Hello", "World"
});
var result = myDictionary.Where(c => c.Value.Contains("Oscar") && c.Value.Contains("Pablo") && c.Value.Contains("John")).ToDictionary(c => c.Key, c => c.Value);
答案 3 :(得分:0)
var namesToFilter = new List { &#34;约翰&#34 ;, &#34;奥斯卡&#34 ;, &#34;巴勃罗&#34;};
Dictionary<int, List<string>> myDictionary = new Dictionary<int, List<string>>
{
{1, new List<string> { "John", "Oscar", "Pablo"}},
{2, new List<string> { "Oscar", "Olivia"}},
{3, new List<string> { "Pablo", "Paula"}},
{4, new List<string> { "Steve", "Stella"}},
};
var matchedKeys= myDictionary
.Where(d => namesToFilter.Where(str => d.Value.Any(v => v == str)).Count() == namesToFilter.Count())
.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
Console.Write(matchedKeys);
答案 4 :(得分:0)
试试这个:
myDictionary.Add(1, new List<string>() { "Oscar", "Pablo" });
myDictionary.Add(2, new List<string>() { "John", "OtherName" });
//Returns item from myDictionary that contains Oscar. Modify where linq query to your necessity
Dictionary<int, List<string>> myNewDic = myDictionary.Where(dicItem => dicItem.Value.Contains("Oscar")).ToDictionary(dicItem => dicItem.Key, dicItem => dicItem.Value);