开发者

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

开发者 https://www.devze.com 2023-04-11 04:29 出处:网络
I have a collection of objects. e.g. List<Subscription> subscription = new List<Subscription>

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?


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.


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

精彩评论

暂无评论...
验证码 换一张
取 消