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”},
};
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();