2

I have a big dictionary and a list (myList). I want to keep the items in myList only if there is an item in my dictionary with the same Title. The problem is that the initialisation of titleList takes long time (2-3 sec). Is there any better way to do that?

var dictionary = r.MyFunction.Where(a condition);
var titleList = dictionary.Select(x => x.Value.Title).ToList()

myList = productsTemp.Where(x => titleList.Contains(x.Title)).ToList();
Dimitris
  • 403
  • 2
  • 8
  • 17
  • 3
    This may add some speed-up's `var titleList = new HashSet(dictionary.Select(x => x.Value))` – Eser Aug 11 '15 at 18:24
  • Are you sure it is not the `myList` creation that takes time? – Magnus Aug 11 '15 at 18:29
  • 2
    Did you try removing the call of the `ToList` method in the second line? I think is not necessary, in the next line you are going to use the `IEnumerable.Contains` method – ocuenca Aug 11 '15 at 18:30
  • What is the target timing you are trying to achieve in list creation? – displayName Aug 11 '15 at 18:36
  • you can combine all to one condition myList = productsTemp.Where(x => r.MyFunction.Where(p=> p.key == condition && P.Value.Title == x.Title).ToList(); – Jophy job Aug 11 '15 at 18:42
  • I think that would take forever (> 2 seconds). – Caramiriel Aug 11 '15 at 19:08
  • Is a ToDictionary() trailer missing from line 1? Is the dictionary actually used elsewhere (not shown in example)? – crokusek Aug 11 '15 at 19:22
  • 2
    Your sample code is incomplete. Please provide complete, compiling sample code. E.g. what is MyFunction (property? of what type?). All answers are just guesswork without this information. – jeroenh Aug 11 '15 at 19:25
  • `Where` does not return a `Dictionary`, so labelling your first `var` as `dictionary` is very confusing. – maraaaaaaaa Aug 11 '15 at 19:55

1 Answers1

0

Hmm, HashSets may optimize the distinct of string as list is not required to be ordered Getting unique items from a list

and as for the code, it should work like this :

    var items = r.MyFunction.Where(a condition).Select(p => p.Value.Title);
    var titleList = new HashSet<string>(items);
    myList = productsTemp.Where(x => titleList.Contains(x.Title)).ToList();

Hope this helps.

EDIT: constructor call is now outside.

Community
  • 1
  • 1
ken lacoste
  • 894
  • 8
  • 22
  • Doesn't this create a new `HashSet` for every iteration of product in `productsTemp` (thus being `O(m*n)`)? Extracting the constructor call would help a lot, performance-wise. – Caramiriel Aug 12 '15 at 08:47