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

后端 未结 2 1676
借酒劲吻你
借酒劲吻你 2021-02-20 02:37

I have a collection of objects. e.g.

List subscription = new List
{
    new Subscription{ Type = \"Trial\", Type = \"Offl         


        
相关标签:
2条回答
  • 2021-02-20 03:16

    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 讨论(0)
  • 2021-02-20 03:28

    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.

    0 讨论(0)
提交回复
热议问题