如何使用LINQ和C#集合中添加项目 [英] How to add an item in a collection using Linq and C#

查看:117
本文介绍了如何使用LINQ和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 }
};

现在我想在使用LINQ此列表中添加更多的项目。我怎样才能做到这一点?

Now I want to add one more item in this list using LINQ. How can I do this?

推荐答案

您没有。 LINQ是的查询的,不加入。您可以通过书面形式添加一个新项目:

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.)

这是不是使用LINQ在所有 - 它的使用对象初始化和简单的列表< T>。新增

This isn't using LINQ at all - it's using object initializers and the simple List<T>.Add method.

这篇关于如何使用LINQ和C#集合中添加项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆