views:

384

answers:

5

I currently have a list called regkey and a string called line_to_delete, which I obviously want to delete from the list. At the moment I'm searching through one element of the list at a time creating substrings as line_to_delete only represents part of the line that I want to delete but is uniquely identifiable within the list.

Anyway what I really need to do is make this more efficient, use fewer resources and be quicker, so are there any ways to do this?

+2  A: 
        List<String> regKey = new List<String> { "test1", "test2" };
        var toDelete = regKey.Where(u => u.Contains(line_to_delete)).SingleOrDefault();
        if (toDelete != null)
            regKey.Remove(toDelete);

or

regkey.RemoveAll(k => k.Contains(line_to_delete));

This will make your deletion more readable, but I'm not sure on the performance compared against your current method.

Michael G
+2  A: 

The simplest way is to use:

var result = list.Where(x => !x.Contains(line_to_delete))

First, make sure this isn’t efficient enough. If it isn’t, you need to resort to advanced data structures to represent your strings, such as a trie. There’s no native support in C# for any such things.

Konrad Rudolph
+3  A: 

Use lamba expressions if it's a List<string>:

list.RemoveAll(x => x.Contains(line_to_delete));
Jamie Ide
This will still have O(n) performance
mfeingold
Yes but since the OP is matching on substrings I don't think a SortedList will help.
Jamie Ide
True, but you have the binary tree in it and you can implement your binary search yourself over the existing tree. It us not this difficult and you will get the O(log(n)) this way
mfeingold
I did not think this all the way through, but maybe you can even fudge the a comparer to use with the standard BinarySearch method so that you do not have to implement it yourself
mfeingold
@mfeingold: As far as I know, most of sorting algorithms usually take O(n*log(n)) and the binary search requires a sorted list.
Chansik Im
Did anyone benchmark this?
JonB
@Chansik this is true, but you only need to sort it once
mfeingold
+2  A: 

Your best bet is to sort the list and use binary search. SortedList will do this for you.. This way you can get O(log(n)) performance

mfeingold
List<T> also has a BinarySearch method: http://msdn.microsoft.com/en-us/library/3f90y839.aspx
R. Bemrose
No, that doesn’t help at all, since the OP is searching for matching substrings.
Konrad Rudolph
What about the cost of sorting the list?
Chansik Im
+1  A: 

I think it is better to use indexOf rather than contains, that speeds up search

so use :

regkey.RemoveAll(k => k.IndexOf(line_to_delete) >=0);
rbg