Is there a trick in creating a generic list of anonymous type?

前端 未结 9 1713
有刺的猬
有刺的猬 2021-01-30 05:25

Sometimes i need to use a Tuple, for example i have list of tanks and their target tanks (they chase after them or something like that ) :

List

        
9条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-30 05:50

    Just to add one more handy bit here. I use Alex's answer on occasion, but it drives me a bit nuts trying to track it back down when I need it, since it's not obvious (I find myself searching for "new {").

    So I added the following little static method (I wish I could make it an extension method, but of what type?):

    public static List CreateEmptyListOf(Func itemCreator)
    {
        return Enumerable
            .Empty()
            .Select(o => itemCreator())
            .ToList();
    }
    
    
    

    This isolates the part that is different each time I need this pattern from those that are the same. I call it like this:

    var emptyList = Ext.CreateEmptyListOf(() => new { Name = default(string), SomeInt = default(int) });
    

    提交回复
    热议问题