Search Unity

Resolved How to optimize this LINQ

Discussion in 'Scripting' started by kei233, Jan 2, 2022.

  1. kei233

    kei233

    Joined:
    Dec 16, 2019
    Posts:
    59
    Code (CSharp):
    1.       var s = datas.GroupBy(d => d.a).OrderByDescending(g => g.Sum(d => d.Dmg))
    2.               .Select(ud => string.Join(":", ud.Key, ud.Sum(d => d.Dmg).NumString()));
    3.         dmmText.text = string.Join("\n", s);
    It's a temporary solution for damage meter, to show damage of units ranking.
    It works, but uses twice of Sum() function.
    Is one time Sum() possible?

    edit: question solved. see #3 if you want to know the solution.
     
    Last edited: Jan 3, 2022
  2. hippocoder

    hippocoder

    Digital Ape

    Joined:
    Apr 11, 2010
    Posts:
    29,723
    If this is called every frame you really should not use LINQ for it, at all. If it's just every so often and you don't mind adding to the GC then maybe just store the results of first sum on a separate line.
     
  3. kei233

    kei233

    Joined:
    Dec 16, 2019
    Posts:
    59
    Code (CSharp):
    1. var s = datas.GroupBy(d => d.a).Select(ud => new { ud.Key, total = ud.Sum(d => d.Dmg) })
    2.             .OrderByDescending(ud => ud.total).Select(ud => string.Join(":", ud.Key, ud.total.NumString()));
    It's now ok.
    The first time I tried Select() first but missing "Total=" for the Sum() then cause grammer error.
     
  4. kei233

    kei233

    Joined:
    Dec 16, 2019
    Posts:
    59
    Thanks for you advice.
    but It's a temporary solution. I consider this as a Linq practice.