Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Lambda Expression on an ObservableCollection

in my Silverlight 4 application, I have an ObservableCollection which consists of objects of a class and is defined by an interface:

interface myInterface()
{
  string Name { get; set; }
  string Value { get; set; }
} 

class myClass() : myInterface
{
  ...
}

ObservableCollection<myInterface> _collection;

Before adding a new element to the collection, I want to make sure, that the Name-Property does not already exists within the current collection elements. As I cannot work with contains, I currently iterate through all elements and check each element manually.

private bool CollectionContainsElement(string name2CheckAgainst)
{
  foreach (myInterface item in _collection)
    if (item.Name.Equals(name2CheckAgainst))
      return true;

  return false;
}

I have read that this can also be achieved via a Lambda Expression, so I wrote the following:

if (!_collection.Contains(p => p.Name == name2CheckAgainst))
{
  ...

But now I get an error, saying that the "lambda expression could not be converted to the Type "myInterface", because it is no delegate-type". (Wording may differ, as I translated it from the german version)

I'm not sure what I have to change to make it work. using System.Linq; is included. And the second question (or maybe the primary question): I have read, that the runtime changes from O(1) for the Contains()-method to O(n) - which isn't faster than my current check. So does it even make sense to change it to using the lambda? And finally, is there probably another method in checking for an existing Name-Property in my class?

Thanks in advance,
Frank

like image 584
Aaginor Avatar asked Nov 28 '11 16:11

Aaginor


1 Answers

  1. You don't have to write a Contains method, the Any method of Linq is already doing that:

    if (!_collection.Any(p => p.Name == name2CheckAgainst))
    
  2. If you want to use a Lambda, you have to change the prototype of your Contains method to accept a Lambda (a lambda is just an alternative way to write an anonymous function):

    private bool CollectionContainsElement(Func<myInterface, bool> lambda)
    {
      foreach (myInterface item in _collection)
        if (lambda(item))
          return true;
    
      return false;
    }
    
  3. Using a lambda here doesn't change the complexity of your function, it's O(n) in both case. So it's just a matter of preference.

like image 80
Kevin Gosse Avatar answered Nov 14 '22 23:11

Kevin Gosse