How to create an empty IOrderedEnumerable<DynamicNode> and IEnumerable<IGrouping<string, DynamicNode>>
Asked Answered
F

2

17

I need a way to create an empty IOrderedEnumerable and IEnumerable<IGrouping<string, DynamicNode>>

//above IGrouping DynamicNode gets stripped out by stackoverflow

Reason: I create 3 empty list types (IOrdered, IGrouping, IEnumerable) then based on some other information (options a user specifies such as order by create date or group by month) I then call a function on it assigning a list of said type.

(short snippet)

//DOESNT WORK THIS IS THE PART I NEED
IEnumerable<DynamicNode> baseList = Enumerable.Empty<DynamicNode>();
IOrderedEnumerable<DynamicNode> orderedList =  (IOrderedEnumerable<DynamicNode>)Enumerable.Empty<DynamicNode>();
IEnumerable<IGrouping<string, DynamicNode>> groupedList = (IEnumerable<IGrouping<string, DynamicNode>>)Enumerable.Empty<DynamicNode>();
//ABOVE DOESNT WORK THIS IS THE PART I NEED

if (order)
{
    if (group)
    {
        groupedList = returnGroupedOrderedList(nodeList, ascending, useFeatured, groupBy, orderBy);
    }
    else
    {
        orderedList = returnOrderedList(nodeList, ascending, useFeatured, orderBy);
    }
}

Anyone know how to do it?

Feeling answered 16/4, 2013 at 9:8 Comment(1)
Why create instances first? Why not just declare the variables? IOrderedEnumerable<DynamicNode> orderedList;. It seems you are setting it again further down anyway.Penelopepeneplain
D
26

The first should work as is:

IEnumerable<DynamicNode> baseList = Enumerable.Empty<DynamicNode>();

The second should work with a little trick:

IOrderedEnumerable<DynamicNode> orderedList =
    Enumerable.Empty<DynamicNode>().OrderBy(x => 1);

The third should work with a little change:

IEnumerable<IGrouping<string, DynamicNode>> groupedList = 
    Enumerable.Empty<IGrouping<string, DynamicNode>>();
Deathtrap answered 16/4, 2013 at 9:11 Comment(0)
S
1

You can always use Enumerable.Empty<T> to generate an empty IENumerable.

Whether you want an IEnumerable of a specific type, or an IEnumerable of IEnumerables the generic input will always work.

Now, if you want an Ordered enumerable then you can build on top of that and order the resulting empty enumerable like so

IOrderedEnumerable<DynamicNode> orderedList = Enumerable
         .Empty<DynamicNode>()
         .OrderBy(x => 1);

and even better, you can use discards since x doesn't matter

IOrderedEnumerable<DynamicNode> orderedList = Enumerable
         .Empty<DynamicNode>()
         .OrderBy(_ => 1);
Scirrhous answered 21/11, 2023 at 15:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.