将项目添加到IEnumerable

编程入门 行业动态 更新时间:2024-10-25 05:12:32
本文介绍了将项目添加到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

本文发布于:2023-11-13 14:19:49,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1584554.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:项目   IEnumerable

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!