简体   繁体   English

如何使用Linq和C#在集合中添加项目

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

I have a collection of objects. 我有一组对象。 eg 例如

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. 现在我想使用LINQ在此列表中添加一个项目。 How can I do this? 我怎样才能做到这一点?

You don't. 你没有。 LINQ is for querying , not adding. LINQ用于查询 ,而不是添加。 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.) (请注意,您不能在同一对象初始值设定项中指定属性Type两次。)

This isn't using LINQ at all - it's using object initializers and the simple List<T>.Add method. 这根本不使用LINQ - 它使用对象初始化器和简单的List<T>.Add方法。

I would suggest using List.Add() : 我建议使用List.Add()

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

LINQ Union() overkill by wrapping a single item by a List<> instance: LINQ Union()通过List<>实例包装单个项目而过度杀伤:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM