2014-09-23 33 views
0

我有兩張關係爲多對多的表格。比方說A和B表。
我也有List<List<int>> TagIdList與ID表的元素ID。
如何才能找到表A中的所有元素,它們都具有TagIdList[i]元素?我只需要來自表A的ID,所以它不一定是來自表的所有TASKS行。多對多 - 從表格中獲取適當的記錄 - EF LINQ

實施例:

答:任務:
ID:1,2,3,4,5,6

B:標籤:
ID:1,2,3 ,4間

AB的聯繫:
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} 

結果:

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(); 

我不能得到的任務,因爲有一個錯誤:

i=0; -> 1 
i=1; -> 2,6 
i=2; -> null 

我試過(從任務IDS)無法創建類型的常量值。在此上下文中僅支持基本類型。

任何想法?

回答

0

我找到解決方案。這可能不是理想的,但工作。

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 
0

你的問題是在這裏: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)) 
+0

我得到了這樣的錯誤:_Can't從 '了System.Collections.Generic.ICollection ' 轉換爲「System.Collections.Generic.IEnumerable _ – Monic 2014-09-23 09:30:22

+0

是TAGS複雜的列表對象而不是整數? – 2014-09-23 09:37:27

+0

查看編輯答案 – 2014-09-23 09:38:42