Remove from List

S

shapper

Hello,

I created a list: List<Theme> Themes.
Each theme has 3 properties: Guid Id, String Title, String Type

I need to remove and item from the list given its id:

Theme theme = MyThemes.Where(t => t.Id == _Id).SingleOrDefault
();
if (theme != null)
MyThemes.Remove(theme);

Is this the way to do this?

I am not sure if I should use something like IndexOf, etc ...

Thanks,
Miguel
 
P

Pavel Minaev

Hello,

I created a list: List<Theme> Themes.
Each theme has 3 properties: Guid Id, String Title, String Type

I need to remove and item from the list given its id:

      Theme theme = MyThemes.Where(t => t.Id == _Id).SingleOrDefault
();
      if (theme != null)
        MyThemes.Remove(theme);

Is this the way to do this?

I am not sure if I should use something like IndexOf, etc ...

You probably should. The above code does two linear scans of the list
- first to find the element by its ID ("Where"), and then to find the
position of the element within the list by the value of that element
("Remove" - it needs an index to remove it). The better approach is to
use FirstIndex - that takes a predicate and returns the index of the
element, which you can then give to RemoveAt. When you only have a
single element with such an ID at all times, this is the most
effecient solution. You could also use RemoveAll, but it will scan the
list to the end, even after finding the first element with the desired
ID (because it expects to deal with more than one if needed).

Note that all of the above only apply if MyThemes is a List<T>. If all
you have is an IList<T> (or some class implementing it which doesn't
provide any of the helper methods that List<T> does - for example,
Collection<T>), then you won't get FirstIndex. You can, however,
emulate it with LINQ as follows:

IList<T> MyThemes;
...
int? indexOfThemeToRemove = MyThemes.Where(t => t.Id == _Id).Select
((t, i) => (int?)i).SingleOrDefault();
if (indexOfThemeToRemove != null) {
MyThemes.RemoveAt((int)indexOfThemeToRemove);
}
 
P

Peter Morris

Can you replace the List<T> reference?


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication32
{
class Program
{
static void Main(string[] args)
{
List<Data> data = new List<Data>();
data.Add(new Data { ID = "1" });
data.Add(new Data { ID = "2" });
data.Add(new Data { ID = "3" });

data = data.Where(d => d.ID != "2").ToList();
}
}

public class Data
{
public string ID { get; set; }
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top