user3733737
user3733737

Reputation: 67

How to add another single anonymous type to LINQ query?

I want to add an item to linq result. Here is my initial query.

var groups = from gr in monitors.groupiddeviceids
                 where gr.device.customerID == customerID
                 group gr by gr.grouping.GroupName into g
                 select new { Group = g.Key, Devices = g.Count() };

I want to put this to a gridview datasource like this:

gvGroups.DataSource = groups.ToList();

But beforehand I want to add one more row to it. The row is of {string, int} format. The row I want to add should read {"Unassigned", 14}

How do I add an item to linq list of annonymous types?

Upvotes: 2

Views: 684

Answers (2)

Tim Schmelter
Tim Schmelter

Reputation: 460028

You can put this anonymous type in an array and use Concat:

var unassigned = new[] { new { Group = "Unassigned", Devices = 14 } };
gvGroups.DataSource = groups.Concat(unassigned).ToList();

If you want it to be the first item: unassigned.Concat(groups).ToList();

If it's actually a database query, that might cause some troubles. Then materialize the query first, for example with ToList:

var groupList = groups.ToList();
groupList.Add(unassigned);
gvGroups.DataSource = groupList;

Upvotes: 6

user3733737
user3733737

Reputation: 67

Got it to work like that, thanks!

gvGroups.DataSource = groups.ToList().Concat(new[] { new { Group = "Unassigned", Devices = 14 } });

Upvotes: 0

Related Questions