Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding an item to IEnumerable

Tags:

c#

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?

like image 367
Craig Avatar asked Feb 17 '11 08:02

Craig


People also ask

How do I add something to IEnumerable?

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");

Is it possible to use Add or AddRange methods on IEnumerable?

Unfortunately, List<T>. AddRange isn't defined in any interface.

What is IEnumerable in C#?

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.

How do I empty my IEnumerable?

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.


1 Answers

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.

like image 105
sloth Avatar answered Nov 02 '22 08:11

sloth