Using a Lambda Expression on an Observed Cell

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

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

class myClass() : myInterface
{
  ...
}

ObservableCollection<myInterface> _collection;

Before adding a new item to the collection, I want to make sure that the property-name does not already exist in the current elements of the collection. Since I cannot work with contains, I currently iterate over all the 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 read that this can also be achieved using 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 cannot be converted to the type" myInterface "because it is not a delegate type." (The wording may be different since I translated it from the German version)

, , . using System.Linq; . (, , ): , O (1) Contains() O (n) - . ? , , Name ?

,

+5
3
  • Contains, Linq :

    if (!_collection.Any(p => p.Name == name2CheckAgainst))
    
  • , Contains, Lambda ( - ):

    private bool CollectionContainsElement(Func<myInterface, bool> lambda)
    {
      foreach (myInterface item in _collection)
        if (lambda(item))
          return true;
    
      return false;
    }
    
  • , O (n) . .

+15

Linq Any(). :

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

, contains - O (1), , HashTable ( ) - ( Equals), , ,

+2

LINQ, -. , , .

, Any - , lambda-

+1

All Articles