Using Linq and C#, add an item to a collection.

c# entity-framework generics linq

Question

I have a collection of objects. e.g.

List<Subscription> subscription = new List<Subscription>
{
    new Subscription{ Type = "Trial", Type = "Offline", Period = 30  },
    new Subscription{ Type = "Free",  Type = "Offline", Period = 90  },
    new Subscription{ Type = "Paid",  Type = "Online",  Period = 365 }
};

Now I want to add one more item in this list using LINQ. How can I do this?

1
11
6/11/2014 3:22:04 PM

Accepted Answer

You don't. LINQ is for querying, not adding. You add a new item by writing:

subscription.Add(new Subscription { Type = "Foo", Type2 = "Bar", Period = 1 });

(Note that you can't specify the property Type twice in the same object initializer.)

This isn't using LINQ at all - it's using object initializers and the simple List<T>.Add method.

17
10/4/2011 1:31:52 PM

Popular Answer

I would suggest using List.Add():

subscription.Add(new Subscriptioin(...))

LINQ Union() overkill by wrapping a single item by a List<> instance:

subscriptions.Union(new List<Subscription> { new Subscriptioin(...) };


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow