借鉴Loop Through An Objects Properties In C#和Using LINQ to loop through inner class properties in outer class collection
在集合(PhaseRepo)中有对象(阶段)的地方,我相信可以在对象(阶段)中指定propertiesOfInterest并创建一个字典来总结这些属性。
请在下面找到我在LinqPad中的尝试。请协助语法或建议其他方法。
谢谢
enum Dir {Up, Dn}
struct BmkKey
{
public Dir Direction;
public string DetailType;
}
class Phase
{
public Dir Direction { get; set; }
public double StartToTerminationBars { get; set; }
public double StartToTerminationPriceChange { get; set; }
public double StartToTerminationGa { get; set; }
public double NotRequiredProperty { get; set; }
}
class PhaseRepo
{
public List<Phase> Phases { get; private set; }
public List<Phase> GetPhases()
{
return new List<Phase>()
{
new Phase() { Direction = Dir.Up, StartToTerminationBars = 3.0, StartToTerminationPriceChange = 4.0, StartToTerminationGa = 4.0},
new Phase() { Direction = Dir.Up, StartToTerminationBars = 6.0, StartToTerminationPriceChange = 8.0, StartToTerminationGa = 4.0},
new Phase() { Direction = Dir.Dn, StartToTerminationBars = 3.0, StartToTerminationPriceChange = -4.0, StartToTerminationGa = -4.0},
new Phase() { Direction = Dir.Dn, StartToTerminationBars = 6.0, StartToTerminationPriceChange = -8.0, StartToTerminationGa = -4.0},
};
}
}
void Main()
{
var phaseRepo = new PhaseRepo();
var phases = phaseRepo.GetPhases();
//phases.Dump();
var propertiesOfInterest = typeof (Phase).GetProperties(BindingFlags.Public | BindingFlags.Instance)
.Where(prop => prop.Name == "StartToTerminationBars"
|| prop.Name == "StartToTerminationPriceChange"
|| prop.Name == "StartToTerminationGa")
.ToList();
//propertiesOfInterest.Dump();
// Please Help...
var test = propertiesOfInterest
.SelectMany(propertyInfo => phases
.Select(phase => phase)
.Select(keyValuePair => new
{
phase.Direction,
keyValuePair.Key,
keyValuePair.Value
})
.Select(arg => new
{
Key = new BmkKey
{
Direction,
DetailType = propertyInfo.Name
},
Value = (double)propertyInfo.GetValue(arg.Value, null)
}))
.GroupBy(grp => grp.Key)
.ToDictionary(grp => grp.Key, grp => x => x.ToList());
test.Dump();
}
预期输出:
答案 0 :(得分:0)
替换下面的部分
//请帮助...
具有以下内容:
var test = propertiesOfInterest
.SelectMany(propertyInfo => phases
.Select(phase => new
{
phase.Direction,
propertyInfo.Name,
Value = (double)propertyInfo.GetValue(phase)
}))
.GroupBy(o => new BmkKey { Direction = o.Direction, DetailType = o.Name })
.ToDictionary(grp => grp.Key, grp => grp.Select(x => x.Value));
这实质上给出了您的问题中所示的预期输出。 (顺序不同;请根据需要使用OrderBy()进行调整。)
您的代码中有一些问题,但是主要的问题是:
此外,以下内容并非错误,但不必要: