Predicate in Net 3.5

  • Thread starter Thread starter shapper
  • Start date Start date
S

shapper

Hello,

I have a List(Of MyClass).
MyClass has two properties: Name and City.

I want to find, without using a loop, if there is a item where name =
NameParameter.

I know that I can use a Predicate but in .NET 2.0 Predicates do not
accepted Parameters.

Because of that I used a Predicate Wrapper.

With .NET 3.5 I know this has changed and now it is much easier to do
something like this.

However, I can't find any example of it.

Can someone, please, help me out?

Thanks,
Miguel
 
Miguel,

Well, like it or not, you are going to have to have a loop somewhere, it
just might not be apparent.

In 3.5, if you want to see if there is any item in the list where
NameParameter = some value, you can do this:


// The list.
List<MyClass> myList = ...;

// The value to check against.
string nameParameterValue = ...;

// Does it contain the value?
bool containsValue = myList.Any(item => item.NameParameter ==
nameParameterValue);

The Any extension method is going to perform the loop for you.
 
shapper said:
I have a List(Of MyClass).
MyClass has two properties: Name and City.

I want to find, without using a loop, if there is a item where name =
NameParameter.

I know that I can use a Predicate but in .NET 2.0 Predicates do not
accepted Parameters.

You can use an anonymous method though:

public bool CheckForItem(string name)
{
return items.Exists(delegate (MyClass item)
{ return item.Name==name;}
);
}
However, I can't find any example of it.

With C# 3 (with or without .NET 3.5) you could use:

public bool CheckForItem(string name)
{
return items.Exists(item => item.Name==name);
}
 
Hello,

I have a List(Of MyClass).
MyClass has two properties: Name and City.

I want to find, without using a loop, if there is a item where name =
NameParameter.

I know that I can use a Predicate but in .NET 2.0 Predicates do not
accepted Parameters.

Because of that I used a Predicate Wrapper.

With .NET 3.5 I know this has changed and now it is much easier to do
something like this.

However, I can't find any example of it.

Can someone, please, help me out?

Thanks,
Miguel

Hi,
I am assuming that you are finding performance problems in this area.
Also assuming that the list contents are unique or you wouldn't be
asking "Is it in the list?"
Any chance of using Dictionary Class<myclass> instead of
List(myClass)?
The Dictionary.ContainsKey method approaches O(1) according to the
documentation.
If you can preSize the dictionary the add function also is O(1)
otherwise O(n).
hth.
Bob
 
Back
Top