Anonymous type collections?

前端 未结 7 1265
醉梦人生
醉梦人生 2021-01-05 02:47

I am looking for best practices for creating collections made from anonymous types.

There are several approaches - this one and most answers on this thread assume th

7条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-05 03:14

    LINQ is the way to go. Assuming you want to fetch the related objects A, B and C of every item in a collection items and sort by the related object A you would go as follows.

    var relatedObjects = items.
           Select(item => new { A = item.A, B = item.B, C = item.C } ).
           OrderBy(item => item.A);
    

    You get a collection of items of an anonymous type with the three properties A, B and C set to the related objects ordered by the related object A.

    I did not verify that, but you should be able to extend the relatedObject collection later. Just do the following to add a single new item. This should work because there is only one anonymous type per assembly I think if the names and types of each property match.

    relatedObjects = relatedObjects.Union(
       Enumerable.Repeat(new { A = someA, B = someB, C = someC }, 1))
    

    Quite ugly because of the Enumerable.Repeat() but becomes quite nice if you union with a collection of new items instead of a single new item.

提交回复
热议问题