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?
What you can do is use the Add extension method to create a new IEnumerable<T> with the added value. var items = new string[]{"foo"}; var temp = items; items = items. Add("bar");
Unfortunately, List<T>. AddRange isn't defined in any interface.
IEnumerable is an interface defining a single method GetEnumerator() that returns an IEnumerator interface. It is the base interface for all non-generic collections that can be enumerated. This works for read-only access to a collection that implements that IEnumerable can be used with a foreach statement.
If the enumerable is always a list and you want to clear it instead make the property type IList. If you're model always has a list and you want to clear it instead, then change the model and access the method that way. Show activity on this post. Just create empty list and asign it.
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)}});
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.
EDIT:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With