Anonymous type collections?

前端 未结 7 1242
醉梦人生
醉梦人生 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条回答
  •  萌比男神i
    2021-01-05 03:17

    One option is to use an example item to create the collection via generic type inference, for example:

        static List CreateEmptyList(T template) {
            return new List();
        }
        void Foo() {
            var list = CreateEmptyList(new { Foo = "abc" });
            list.Add(new { Foo = "def" });
            //...
        }
    

    You can also do this without creating an instance (but using an anonymous method that never gets caller), but I don't think it saves anything really... we might not create an instance of the object, but we do create an instance of a delegate, so not much of a saving...

    You also mention sorting the data; see the reply here for a way to use List.Sort with a lambda, and hence with anonymous types - i.e.

    list.Sort(x=>x.Foo);
    

提交回复
热议问题