Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/276.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何根据匹配名称将数据列表类型值替换为字典值_C# - Fatal编程技术网

C# 如何根据匹配名称将数据列表类型值替换为字典值

C# 如何根据匹配名称将数据列表类型值替换为字典值,c#,C#,我有一本字典和一份数据清单 如果字典中存在Type,我只需要数据列表中的数据lstData 我需要用字典中的名称替换lstData的Type名称type1带“X”和type3带type3 var dictionary = new Dictionary<string, string> { { "type1", "X" }, { "type3", "type3" } }; var lstData

我有一本字典和一份数据清单

  • 如果字典中存在
    Type
    ,我只需要数据列表中的数据
    lstData

  • 我需要用字典中的名称替换
    lstData
    Type
    名称
    type1
    带“X”和
    type3
    type3

    var dictionary = new Dictionary<string, string> { { "type1", "X" }, { "type3", "type3" } };
    
        var lstData = new List<Data>
        {
            new Data {Name = "N1", Type = "type1"},
            new Data {Name = "N1", Type = "type2"},
            new Data {Name = "N2", Type = "type3"},
        };
    
    var dictionary=newdictionary{{“type1”,“X”},{“type3”,“type3”};
    var lstData=新列表
    {
    新数据{Name=“N1”,Type=“type1”},
    新数据{Name=“N1”,Type=“type2”},
    新数据{Name=“N2”,Type=“type3”},
    };
    
  • 通过以下问题,我能够实现第1部分),如何完成第2部分

    var x=lstData.Where(a=>newlist(dictionary.Keys).Any(b=>b==a.Type));
    
    预期产出应为:

    x = new List<Data>
            {
                new Data {Name = "N1", Type = "X"},
                new Data {Name = "N2", Type = "type3"},
            };
    
    x=新列表
    {
    新数据{Name=“N1”,Type=“X”},
    新数据{Name=“N2”,Type=“type3”},
    };
    
    使用
    ContainsKey
    将更有效,尤其是对于大型数据集

    然后,您可以使用
    选择
    来创建新的
    数据
    对象:

    var x = listData
        .Where(d => dictionary.ContainsKey(d.Type)) // Part 1
        .Select(d => new Data { Name = d.Name, Type = dictionary[d.Type] }) // Part 2
        .ToList();
    

    谢谢欣赏
    var x = listData
        .Where(d => dictionary.ContainsKey(d.Type)) // Part 1
        .Select(d => new Data { Name = d.Name, Type = dictionary[d.Type] }) // Part 2
        .ToList();