在c#

时间:2017-08-29 13:59:31

标签: c# linq

我有一个字典,其中id为key,value将是它将被标记为的id(实际上是ref数据)。

还有一个列表仅包含ID,但具体名称。

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

e.g。如果列表2中的id有clubbed id(我们从ref字典中检查),那么我们只需要保存clubbed id 让我们假设列表2中的ID是1,10,21。因此,我只需要保存一个id,即俱乐部,即21,但不能保存1和10.在这种情况下,我们只保存1而不是3。

如果这些id没有任何棍棒id,则会保存3个ID(1,10,21)。

更新:

字典有1到100个ID,有些id有棍棒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);

首先,我将检查列表2中的所有三个ID是否都在引用字典中。然后将在字段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有俱乐部ID,这是正确的。

但是你可以在我的参考词典中看到,ids 1和10的clubbed id为21.因此,在list3中我只需要存储一个值21(只有俱乐部id删除另一个1和10)

任何帮助。

1 个答案:

答案 0 :(得分: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

相关问题