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

前端 未结 9 1702
有刺的猬
有刺的猬 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条回答
  •  闹比i
    闹比i (楼主)
    2021-01-30 05:47

    Here's a hack:

    var myList = Enumerable.Empty()
        .Select(dummy => new { AttackingTank = default(Tank), TargetTank = default(Tank), })
        .ToList();
    

    If Tank is a class type, you can write (Tank)null instead of default(Tank). You can also use some Tank instance you happen to have at hand.


    EDIT:

    Or:

    var myList = Enumerable.Repeat(
        new { AttackingTank = default(Tank), TargetTank = default(Tank), },
        0).ToList();
    

    If you make a generic method, you won't have to use Enumerable.Empty. It could go like this:

    static List GetEmptyListWithAnonType(TAnon dummyParameter)
    {
        return new List();
    }
    

    It is to be called with the TAnon inferred from usage, of course, as in:

    var myList = GetEmptyListWithAnonType(new { AttackingTank = default(Tank), TargetTank = default(Tank), });
    

提交回复
热议问题