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(...) };
精彩评论