在Parts类中,我们有Data字典,例如,它包含键“ Number”和值“ 1”。键始终被称为“数字”,并且值始终是一些数字1,2,3等的字符串。我想将具有键“数字”及其值的所有项分配给一个变量(列表),然后进行分组他们通过部件中的ID。因此,最终结果应该是零件,编号及其值中的ID。
public class People
{
public List<Parts> Parts { get; set; }
}
public class Parts
{
public string Name {get;set;}
public string Id {get;set;}
public Dictionary<string,string> Data {get;set}
}
var msf = new People();
当前我的示例不适用于linq:
var temp = msf
.Parts
.Select(s => s.Data.Keys.Where(key => key.Contains("Number"))
.ToList()
.Select(s = > s.Value));
有人可以使用linq为我提供此场景代码的更好解决方案吗?
"People":[
"id":"1234567"
"Parts":[
"id":"234567",
"name":"Lqlq"
"Data":{
"number" : "1"
}
"id":"3424242",
"name":"Lqlq2"
"Data":{
"number" : "2"
}
]
]
答案 0 :(得分:3)
这应该为您提供一个Dictionary<string, List<string>>
,其中包含每个“数字”值的ID字符串列表:
var idsByNumber = msf.Parts.Where(p => p.Data.ContainsKey("number")) // filter for all that have a number
.Select(p => new { ID = p.ID, Number = p.Data["number"] }) // select ID and the number value
.GroupBy(x => x.Number) // group by number
.ToDictionary(g => g.Key, g => g.ToList()); // create dictionary number -> id list
答案 1 :(得分:2)
这是另一种语法。
var temp = from part in msf.Parts
where part.Data["Number"] == "2"
select part;
通常,使用MCVE询问您的问题是一个好主意-这是可以粘贴在Linqpad中的一些代码:
void Main()
{
var msf = new People() {
Parts = new List<Parts> {
new Parts { Name = "Lqlq", Id = "234567", Data = new Dictionary<string, string> { { "Number", "1"} } },
new Parts { Name = "Lqlq2", Id = "3424242", Data = new Dictionary<string, string> { { "Number", "2"} } },
}
};
var temp = from part in msf.Parts
where part.Data["Number"] == "2"
select part
;
temp.Dump();
}
public class People
{
public List<Parts> Parts { get; set; }
}
public class Parts
{
public string Name { get; set; }
public string Id { get; set; }
public Dictionary<string, string> Data { get; set; }
}