Ale61268967
Ale61268967

Reputation: 117

c# delete a List from a List<List<>>

I have a List<List<Ricerca>> where my object Ricerca has the following structure:

 public class Ricerca    {
    public int id;

    public double Altezza;
    public double lunghezza;
    }

I want to delete from the List<List<Ricerca>> all the lists that contain an OBJECT Ricerca with id present in a list of ids. The code I am using to do so follows but it's slow. Is there a better way? I wanted to use the linq but I can't figure out how.

public void CleanCombinations(ref List<List<Ricerca>> list,List<Combinazione> combs)
{

    for (int i = 0; i < list.Count; i++)
    {
        bool remove = false;
        for (int k = 0; k < list[i].Count; k++)
        {
            foreach (Combinazione cbn in combs)
            {
                foreach (int ind in cbn.index)
                {
                    if (ind == list[i][k].id)
                    {
                        remove = true;
                    }
                }
            }
        }

        if (remove)
        {
            list.RemoveAt(i);
            i--;
        }

Upvotes: 0

Views: 380

Answers (2)

Ctznkane525
Ctznkane525

Reputation: 7465

Brevity of code will not help your computational problem.

As long as you have an unsorted list, the fastest search is going to be O(n), meaning worst case you have to iterate through all the items.

Now in your situation, you continue iterating after finding the value. My recommendation would be to exit the loop when finding the item, so your average case becomes n/2 instead of n.

If you have many searches and the order of the items is not important, then the List is not a good choice. I recommend using a dictionary where you can do a search by key in O(1).

If order of the items is important, then go with a SortedList. You'll get O(log n) search.

Upvotes: 0

Stevo
Stevo

Reputation: 1434

The following Linq will do it.

var ids = new[] { 2, 3 };
list.RemoveAll(subList => subList.Any(item => ids.Contains(item.id)));

Upvotes: 3

Related Questions