Anonymous type collections?

前端 未结 7 1197
醉梦人生
醉梦人生 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:32

    If you're happy with an array, you can use an array initializer:

    var items = new[] {
        new { Foo = "def" },
        new { Foo = "ghi" },
        new { Foo = "jkl" }
    };
    

    You can then call ToList() if you want to get a List<T> out. Marc's solution will be slightly more efficient than calling ToList() due to not needing the extra copying, but I think I'd probably use the "array and then ToList()" solution in most cases as there's less clutter. Of course, if performance is crucial for that bit of code, it changes things.

    EDIT: As you're iterating over a collection, just use Select:

    var anonymousItems = items.Select (item => new { Foo=item.Foo, 
                                                     Bar=item.Other })
                              .ToList();
    
    0 讨论(0)
提交回复
热议问题