2012-07-11 89 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操作