可以組kList
第一,然後用SequenceEqual
與tid
,這裏是一個演示
List<KeyValuePair<string, int>> kList = new List<KeyValuePair<string, int>>()
{
new KeyValuePair<string, int>("001",1),
new KeyValuePair<string, int>("001",2),
new KeyValuePair<string, int>("002",1),
new KeyValuePair<string, int>("003",3),
new KeyValuePair<string, int>("004",1),
new KeyValuePair<string, int>("004",2)
};
List<int> tid = new List<int>() { 1, 2 };
var query = kList.GroupBy(i => i.Key)
.Where(g => g.Select(j => j.Value).Distinct().OrderBy(i => i).SequenceEqual(tid))
.SelectMany(g => g.Select(x => x.Key)).Distinct();
Console.WriteLine(string.Join(",", query));
,也許SequenceEqual
有一些問題,如果你想contains
所有tid
,不Equal
,那麼你可以使用Intersect
來SequenceEqual
,代碼是這樣的
List<KeyValuePair<string, int>> kList = new List<KeyValuePair<string, int>>()
{
new KeyValuePair<string, int>("001",1),
new KeyValuePair<string, int>("001",2),
new KeyValuePair<string, int>("002",1),
new KeyValuePair<string, int>("001",3),//special one
new KeyValuePair<string, int>("003",3),
new KeyValuePair<string, int>("004",1),
new KeyValuePair<string, int>("004",2)
};
List<int> tid = new List<int>() { 1, 2 };
var query = kList.GroupBy(i => i.Key)
.Where(g => g.Select(j => j.Value).Distinct().Intersect(tid).Count()==tid.Count)
.SelectMany(g => g.Select(x => x.Key)).Distinct();
Console.WriteLine(string.Join(",", query));
是LINQ必須的嗎?我可以給與SQL查詢解決方案。 – niksofteng
不,我想在LINQ – ADMIN
也許這[intersect](http://stackoverflow.com/a/7565274/1257607)答案可以幫助 – DanielV