LINQ将项列表转换为具有冗余值的行查找



我相信标题没有多大帮助,我会尽量在这里更好地解释…希望你能帮助我。

我有这个类

public class ItemValue
{
public string SetId {get; set;}
public string ItemId {get; set;}
public string Value {get; set;}
}

我有一个这个类的对象集合,比如这个

IEnumerable<ItemValue> = new List<ItemValue>()
{
new ItemValue
{
SetId = "S1",
ItemId = "I1",
Value = "S1I1V",
},
new ItemValue
{
SetId = "S1",
ItemId = "I2",
Value = "S1I2V",
},
new ItemValue
{
SetId = "S1",
ItemId = "I3",
Value = "S1I3V",
},
new ItemValue
{
SetId = "S2",
ItemId = "I1",
Value = "S2I1V",
},
new ItemValue
{
SetId = "S2",
ItemId = "I2",
Value = "S2I2V1",
},
new ItemValue
{
SetId = "S2",
ItemId = "I2",
Value = "S2I2V2",
},
new ItemValue
{
SetId = "S2",
ItemId = "V3",
Value = "S2I3V",
}
};

注意,有两个实例的SetId="S2"ItemId="I2"具有不同的值

我需要的是用LINQ

把这个集合映射成这样的东西
var expectedResult = new Lookup<string, IDictionary<string, string>>()
{
["S1"] = new Dictionary<string, string>() 
{
{ ["I1"] = "S1I1V" },
{ ["I2"] = "S1I2V" },
{ ["I3"] = "S1I3V" },
},
["S2"] = new Dictionary<string, string>() 
{
{ ["I1"] = "S2I1V" },
{ ["I2"] = "S2I2V1" },
{ ["I3"] = "S2I3V" },
},
["S2"] = new Dictionary<string, string>() 
{
{ ["I1"] = "S2I1V" },
{ ["I2"] = "S2I2V2" },
{ ["I3"] = "S2I3V" },
}
};

我自己不擅长LINQ,经过一些不成功的LINQ试验和使用一堆foreach和if的丑陋解决方案后,我现在联系你,请为此获得一些想法。

如果您需要任何其他信息,请告诉我

非常感谢你提前…

你可以用GroupBy和ToDictionary/tollookup做类似的事情

var dict = items.GroupBy(i => i.SetId)
.ToDictionary(
group => group.Key,
group => group.ToLookup(i => i.ItemId, i => i.Value));
dict["S2"]["I2"].ToList() // usage example

另一个选项是

var dict2 = items.ToLookup(i => (i.SetId, i.ItemId), i => i.Value);
dict2[("S2", "I2")].ToList() // usage example

相关内容

  • 没有找到相关文章

最新更新