Reputation: 543
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?
Upvotes: 5
Views: 13662
Reputation: 624
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);
Upvotes: 2
Reputation: 6755
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.
Upvotes: 2
Reputation: 7134
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
Upvotes: 3
Reputation: 49301
Use lamba expressions if it's a List<string>
:
list.RemoveAll(x => x.Contains(line_to_delete));
Upvotes: 6
Reputation: 546083
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.
Upvotes: 2