我有两张有关系的桌子-多对多。比方说A和B桌。
我还有带有B表元素I的List<List<int>> TagIdList
。
我如何从表A中找到所有TagIdList[i]
元素的所有元素?我只需要表A中的I,所以它不必是表中的所有任务行。
示例:
A:任务:
id: 1,2,3,4,5,6
B:标签:
id: 1,2,3,4
A链接:
1-2;1-3;2-1;2-2;5-3;5-4;6-1;6-6;
List<List<int>> TagIdList //(ids from TAGS)
TagIdList[0]= {2,3}
TagIdList[1]= {1}
TagIdList[2]= {2,6}
结果:(任务ids)
i=0; -> 1
i=1; -> 2,6
i=2; -> null
我试过:
List<int> tags = model.TagIdList[i].IdList; //I've got it from my View
List<TASKS> tasks = myEntity.TASKS.Where(t => t.TAGS == tags).ToList();
我无法获得任务,因为有一个错误:无法创建类型的常量值。在此上下文中只支持基本类型。
有什么想法吗?
发布于 2014-09-29 14:26:30
我找到了解决办法。也许不太理想,但很管用。
List<int> tags = model.TagIdList[i].IdList;
List<List<int>> whole_list = new List<List<int>>();
foreach (var t in tags) //I'm looking for every tasks' ids in every given tag
{
var temp = myEntity.TAGS.Find(t).TASKS.Select(task => task.Id).ToList();
whole_list.Add(temp);
}
//now I want first list from whole_list to compare with the other lists
List<int> collection = whole_list[0]; //collection it's tasks
whole_list.Remove(collection);
//I'm taking a part which is common to all lists from whole_list
foreach (List<int> k in whole_list)
{
var temp = collection.Intersect(k);
collection = temp.ToList();
}
//the collection is now what I wanted for TagIdList[i] - every task which has every tags from TagIdList[i].IdList
发布于 2014-09-23 09:04:50
你的问题在这里:myEntity.TASKS.Where(t => t.TAGS == tags)
如果我明白这个问题正确的话,你需要这样的东西:
两个int列表的比较方法(取自here)
public static bool ScrambledEquals<T>(IEnumerable<T> list1, IEnumerable<T> list2) {
var cnt = new Dictionary<T, int>();
foreach (T s in list1) {
if (cnt.ContainsKey(s)) {
cnt[s]++;
} else {
cnt.Add(s, 1);
}
}
foreach (T s in list2) {
if (cnt.ContainsKey(s)) {
cnt[s]--;
} else {
return false;
}
}
return cnt.Values.All(c => c == 0);
}
而不是在linq表达式中使用此方法:
myEntity.TASKS.AsEnumerable().Where(t => ScrambledEquals<int>(t.TAGS.Select(tag=>tag.id).ToList(),tags))
https://stackoverflow.com/questions/25990429
复制相似问题