2017-08-29 68 views
-1

我有一个字典有ids作为关键和价值将是它的标准杆(它实际上是参考数据)。将多个值合并为一个在c#

还有一个列表只包含id,但具体名称。

第一个列表有100个不同的ID,从1到100. 我正在检查列表2中的特定名称的ID是否出现在列表1中。如果它们存在,则保存这些ID。但是它有一个特殊的条件。

例如如果列表2中的id有棍棒ID(我们正在从参考字典中检查),那么我们只需保存棍棒ID 让我们假设列表2中的ID是1,10,21。因此,我只需要保存一个id,这是棍棒状的一个,即21,但不能保存1和10.在这种情况下,我们只保存1而不是3.

如果这些ids没有任何clubbed id,那么3个id将被保存(1,10,21)。


更新时间:

字典有1到100的ID和一些IDS的有杵id和一些不要

Dictionary<int,string> dict = new Dictionary<int,string>(); 
//Key is id and the value is clubbedid 
dict.Add(1,"21"); 
dict.Add(10,"21"); 
dict.Add(21,"None"); 
// etc 

//In the list 2 we have ids for specific name 
List<int> list2 = new List<int>(); 
list2.Add(1); 
list2.Add(10); 
list2.Add(21); 

首先,我要检查所有的三个ID列表2是否然后将字段Id中其他对象列表中的值赋值。

foreach(int value on list2) 
{ 
    if(dict.ContainsKey(value)) 
    { 
     List<class> list3 = new List<class> list3(); 
     list3.Id = value; 
    } 
} 

因此,我在list3的id字段中逐个添加了三个ID 1,10,21。现在list3包含三个id。在简单的情况下,这是正确的,没有一个id有clubbed id。

但是正如你可以在我的参考字典中看到的,ids 1和10的clubbed id为21.因此,在list3中我只能存储一个值为21(只有clubbed id去掉另一​​个1和10 )

任何帮助。

+3

我不知道你所说的“杵”的意思在这里... – Chris

+1

请张贴一些代码 – adiga

+3

他们是否密封? – buffjape

回答

0

你的问题不是特别清楚 - 根据目前的评论。


为了有一个刺在这 - 假设list1IEnumerable<int>list2Dictionary<int,int[]>那么我认为你正在试图做的是沿着以下

// numbers 1-100 
var list1 = Enumerable.Range(1,100).ToList(); 

// 3 entries 
var list2 = new Dictionary<int,int[]>(){ 
     {1,new[]{21}}, 
     {10,new[]{21}}, 
     {21,new int[0]} 
}; 

var result = list2.SelectMany(item => { 
    if(!list1.Contains(item.Key)) 
     return Enumerable.Empty<int>(); 
    if(item.Value != null && item.Value.Length>0) 
     return item.Value; 
    return new[]{item.Key}; 
}).Distinct(); 

直播的线例如:http://rextester.com/RZMEHU88506


已经更新了你的问题,这可能工作为您提供:

var list3 = list2.Select(x => { 
    int value = 0; 
    // if the dict contains the key and the value is an integer 
    if(dict.ContainsKey(x) && int.TryParse(dict[x], out value)) 
     return value; 
    return x; 
}) 
.Distinct() 
.Select(x => new MyClass(){ Value = x }) 
.ToList(); 

活生生的例子:http://rextester.com/KEEY8337

+0

我用代码片段更新了这个问题。 – Ritesh

+0

任何帮助将不胜感激,并添加代码片段。 – Ritesh

+0

@Ritesh下次使用*实际编译的代码片段*!查看更新的答案。 – Jamiec