【发布时间】:2018-10-27 09:50:16
【问题描述】:
我正在寻找一种更好的方式来订购我的收藏品。我有 json 对象,如下所示,
[{
"Type": "A",
"Bs": [{
"Type": "B",
"Cs": [{
"Type": "C",
"Ds": [{
"Type": "D",
"Es": [{
"Type": "E",
"Total": 10
},
{
"Type": "E",
"Total": 20
},
{
"Type": "E",
"Total": 1
}]
},
{
"Type": "D",
"Es": [{
"Type": "E",
"Total": 100
},
{
"Type": "E",
"Total": 50
},
{
"Type": "E",
"Total": 10
}]
}]
}]
},
{
"Type": "B",
"Cs": null
}]
}]
我想以更好的方式按内部集合(E 模型)订购。我已经在 SortByTotal 方法中实现了我想要的,但我想改进它。这是我的解决方案。
private static void SortByTotal(List<A> list)
{
foreach (var a in list)
{
if (a.Bs == null) continue;
foreach (var b in a.Bs)
{
if (b.Cs == null) continue;
foreach (var c in b.Cs)
{
if (c.Ds == null) continue;
foreach (var d in c.Ds)
{
if (d.Es == null) continue;
d.Es = d.Es.OrderBy(x => x.Total).ToList();
}
}
}
}
}
这是我所有的模型类和示例对象的代码
注意:基本需要改进SortByTotal方法
class Program
{
static void Main(string[] args)
{
var list = new List<A>
{ new A { Bs = new List<B> { new B { Cs = new List<C> { new C { Ds = new List<D> {
new D {
Es = new List<E> { new E {Total = 10}, new E {Total = 20}, new E {Total = 1} }
},
new D {
Es = new List<E> { new E {Total = 100}, new E {Total = 50}, new E {Total = 10} }
}
} } } }, new B() } } };
Console.WriteLine("before sort");
var beforeSortList = list;
SortByTotal(list);
Console.WriteLine("after sort");
var afterSortList = list;
Console.ReadKey();
}
private static void SortByTotal(List<A> list)
{
foreach (var a in list)
{
if (a.Bs == null) continue;
foreach (var b in a.Bs)
{
if (b.Cs == null) continue;
foreach (var c in b.Cs)
{
if (c.Ds == null) continue;
foreach (var d in c.Ds)
{
if (d.Es == null) continue;
d.Es = d.Es.OrderBy(x => x.Total).ToList();
}
}
}
}
}
}
class A
{
public string Type { get; set; } = "A";
public List<B> Bs { get; set; }
}
class B
{
public string Type { get; set; } = "B";
public List<C> Cs { get; set; }
}
class C
{
public string Type { get; set; } = "C";
public List<D> Ds { get; set; }
}
class D
{
public string Type { get; set; } = "D";
public List<E> Es { get; set; }
}
class E
{
public string Type { get; set; } = "E";
public int Total { get; set; }
}
【问题讨论】:
-
你知道你的变量是引用吗?
beforeSortList和afterSortList指向同一个集合... -
是的,我知道,我只是想用这个变量更好地描述。如果它可以混合,我可以删除它们。这些变量不是重点。
标签: c# performance linq lambda