2012-07-11 87 views
0
Dictionary<int, string> lstSrc = new Dictionary<int, string>(); 
      Dictionary<int, string> lstDest = new Dictionary<int, string>(); 

     lstSrc.Add(1, "All"); 
     lstSrc.Add(2, "Weekday"); 
     lstSrc.Add(3, "WeekEnd"); 

     lstDest.Add(1, "All"); 
     lstDest.Add(2, "X1"); 
     lstDest.Add(3, "X2"); 
     lstDest.Add(4, "Weekday"); 
     lstDest.Add(5, "WeekEnd"); 

比較,只有當名稱匹配來源和目標如何在列表中映射Id?

var matchingItems = lstDest 
        .Where(l2 => lstSrc.Any(l1 => l1.Value.Equals(l2.Value))).ToList(); 
       matchingItems.AddRange(lstDest.Except(matchingItems)); 

該查詢給出結果作爲影像附加看看如何得到這一結果,而無需使用LINQ?

我怎麼能做到這一點?

[1]: http://i.stack.imgur.com/FLicZ.png 
+0

所以,你想要的一切塔t在第一個列表還是在第二個列表中? – phg 2012-07-11 15:35:59

+0

我有一個相當困難的時間來理解你的問題。你能更清楚嗎?頂部的2個代碼框是否代表示例列表?或者它們是否代表列表中的單個元素? – 2012-07-11 15:37:02

+0

@phg:第一個列表 – user662285 2012-07-11 15:38:39

回答

1

爲了得到相匹配的項目,你可以使用這樣的查詢:

var matchingItems = List2 
    .Where(l2 => List1.Any(l1 => l1.TimeGroupName.Equals(l2.TimeGroupName)); 
matchingItems.AddRange(List2.Except(matchingItems))); 

編輯:相當於沒有使用LINQ:(!這很容易忘記很多鍋爐板的LINQ如何節省你寫)

// Get the matching items 
List<TIMEGROUPINFO> matchingItems = new List<TIMEGROUPINFO>(); 
foreach (TIMEGROUPINFO l1 in List1) 
{ 
    foreach (TIMEGROUPINFO l2 in List2) 
    { 
     if (l1.TimeGroupName.Equals(l2.TimeGroupName)) 
     { 
      matchingItems.Add(l1); 
      continue; 
     } 
    } 
} 

// Append the items from List2 which aren't already in the list: 
foreach (TIMEGROUPINFO l2 in List2) 
{ 
    bool exists = false; 
    foreach (TIMEGROUPINFO match in matchingItems) 
    { 
     if (match.TimeGroupName.Equals(l2.TimeGroupName)) 
     { 
      // This item is already in the list. 
      exists = true; 
      break; 
     } 
    } 

    if (exists = false) 
     matchingItems.Add(l2); 
} 
+0

這是不可能的 - 我認爲我的補充應該提供所需的結果。 – Filburt 2012-07-11 16:01:24

+0

@Staurt:你的Linq查詢給了我預期的結果,但我使用了Dot Net 2.0,所以linq概念在那裏。如何在不使用LINQ的情況下實現同樣的效果? – user662285 2012-07-12 04:59:56

+0

@Stuart:請參閱我編輯的問題。 – user662285 2012-07-12 10:22:18

0

我知道你想對列表2執行一個基於列表1的查詢.Linq對此非常有用。

所以,如果你寫的東西像

//List1Element is a single element in the first list. 
List1Element = List1[i]; 

List2.Where(l2 => l2.TimeGroupName == List1Element.TimeGroupName).ToList(); 

這可能做到什麼,我認爲你要完成的任務。

如果你想在一次匹配整個列表1,您可以通過所有的列表1元素迭代,或者你可以看看Linq Join操作