C # лучший способ заказа вложенных внутренних коллекций - PullRequest
0 голосов
/ 27 октября 2018

Я ищу заказ моей коллекции с лучшим способом.У меня есть объект 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();
                }
            }
        }
    }
}

Вот мои все коды с модельными классами и образцом объекта

note : в основном необходимо улучшить 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; }
}

1 Ответ

0 голосов
/ 27 октября 2018

Вы можете достичь своего Sorting с помощью SelectTokens метода JToken.

1) Разобрать свой json на JToken.

2) Получить все токены с ключом какEs по всему JToken.

3) Выберите каждый объект json как JObject.

4) И отсортируйте все Jobject s с помощью OrderBy.

5) Наконец напечатайте свой результат.

class Program
{
    static void Main(string[] args)
    {
        string str = File.ReadAllText(@"Path to your json file");

        //Step 1
        JToken jToken = JToken.Parse(str);

        //Step 2 to 4
        var result = jToken.SelectTokens("..Es").Select(x => x.Select(y => (JObject)y).OrderBy(z => z["Total"])).ToList();

        //Step 5
        foreach (var i in result)
        {
            foreach (var j in i)
                Console.WriteLine($"Type: {j["Type"]} \t Total: {j["Total"]}");
            Console.WriteLine();
        }

        Console.ReadLine();
    }
}

Выход:

enter image description here

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...