将项目添加到IEnumerable [英] Adding an item to IEnumerable

查看:77
本文介绍了将项目添加到IEnumerable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我的对象的List<>,但现在需要将其更改为IEnumerable<>.所以,我有这个:

I had a List<> of my objects, but now need to change it to an IEnumerable<>. So, I have this:

public IEnumerable<TransactionSplitLine> TransactionSplitLines { get; set; }

但是,我不能再这样做:

However, I can no longer do:

reply.TransactionSplitLines.Add(new TransactionSplitLine
                                                    {Amount = "100", Category = "Test", SubCategory = "Test More", CategoryId=int.Parse(c)});

我现在应该如何添加项目?

How should I be adding items now?

推荐答案

您可以使用Concat执行以下操作:

You could do something like the following, using Concat:

reply.TransactionSplitLines = 
    reply.TransactionSplitLines.Concat(new []{new TransactionSplitLine                                                     {
                                                 Amount = "100", 
                                                 Category = "Test", 
                                                 SubCategory = "Test More",
                                                 CategoryId = int.Parse(c)}});

这基本上会创建一个新的 IEnumerable .鉴于您的用例信息不足,很难说什么是最佳的解决方案.

That basically creates a new IEnumerable. It's hard to say what's the best solution in your case, since there are not enough information about your use case.

请注意, List< T> 实现了 IEnumerable< T> .因此,例如,如果您需要传递 IEnumerable< T> 作为参数,则还可以传递 List< T> 作为参数,也许可以显式调用 AsEnumerable() .因此,也许您可​​以坚持使用List而不是IEnumerable.

Please note that List<T> implements IEnumerable<T>. So if you need to pass an IEnumerable<T> as a parameter for example, you can also pass a List<T> instead, maybe calling explicitly AsEnumerable() on your list first. So maybe you could stick with a List instead of an IEnumerable.

这篇关于将项目添加到IEnumerable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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