c# modifying structs in a List

后端 未结 5 809
天涯浪人
天涯浪人 2021-01-01 19:57

Short question: How can I modify individual items in a List? (or more precisely, members of a struct stored in a List?)

Full e

5条回答
  •  情深已故
    2021-01-01 20:18

    If subItems was changed to a concrete List instead of the interface IList, then you'd be able to use the Sort method.

    public List subItems;
    

    So your whole loop becomes:

    foreach (slotInfo sInf in gAllCats[c].items)
        sInf.subItems.Sort();
    

    This won't require the contents of the struct to be modified at all (generally a good thing). The struct's members will still point to exactly the same objects.

    Also, there are very few good reasons to use struct in C#. The GC is very, very good, and you'd be better off with class until you've demonstrated a memory allocation bottleneck in a profiler.

    Even more succinctly, if items in gAllCats[c].items is also a List, you can write:

    gAllCats[c].items.ForEach(i => i.subItems.Sort());
    

    Edit: you give up too easily! :)

    Sort is very easy to customise. For example:

    var simpsons = new[]
                   {
                       new {Name = "Homer", Age = 37},
                       new {Name = "Bart", Age = 10},
                       new {Name = "Marge", Age = 36},
                       new {Name = "Grandpa", Age = int.MaxValue},
                       new {Name = "Lisa", Age = 8}
                   }
                   .ToList();
    
    simpsons.Sort((a, b) => a.Age - b.Age);
    

    That sorts from youngest to oldest. (Isn't the type inference good in C# 3?)

提交回复
热议问题