Multidimensional arrays do not implement IEnumerable, or do they?

后端 未结 4 1323
广开言路
广开言路 2021-01-13 14:55

For the reasons that I still do not understand (see this SO question) multidimensional arrays in CLR do not implement IEnumerable. So the following doe

4条回答
  •  离开以前
    2021-01-13 15:33

    Tip: instead of Cast() use a typed range variable


    Samuel stated:

    In C#, you can simulate this by using

    var q = from e in m.Cast() select e;
    // q is of type IEnumerable
    
    
    
    

    which is of course correct as far as mimicking VB in C# is concerned, but you would loose your type information. Instead, it is much easier and as it turns out, slightly better readable, to simply declare your range variable.

    The following compiles, performs better, is type safe and does not loose type information:

    var m = new int[2, 2] { { 1, 2 }, { 3, 4 } };
    var q = from int e in m select e;
    // q is of type IEnumerable
    

    In the original suggestion, you would have an IEnumerable, using int e you change that into IEnumerable, which has its advantages.

    提交回复
    热议问题