user946393
user946393

Reputation:

How to add an item in a collection using Linq and C#

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?

Upvotes: 11

Views: 31533

Answers (2)

sll
sll

Reputation: 62504

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(...) };

Upvotes: 6

Jon Skeet
Jon Skeet

Reputation: 1500425

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.

Upvotes: 17

Related Questions