How do I use the Find method on a generic List collection

T

Tony Johansson

Hello!

Assume I have the class shown below and it's stored in a generic List.
If I want to find the Value for a specific Id how do I use the find method.
We can assume that the generic List collection is named
myWorkSheetRowParameterList

public class WorkSheetRowParameter
{
public string WorkSheetRowId {get; set};
public string Id {get;set};l
public string Type {get;set};
public string Value {get;set};
public string Disabled{get;set};
public string ParameterName{get;set};
public string ParameterDuplicate{get;set};
}

//Tony
 
M

Marc Gravell

You need a "predicate" - i.e. a condition to match, expressed as a
delegate. Since you are using C# 3.0, this is simply:

string id = "abc"; // etc
WorkSheetRowParameter row =
myWorkSheetRowParameterList.Find(
x => x.Id == id);

Marc
 
M

Marc Gravell

oh, I forgot - you'll need to get .Value afterwards.

Actually, with LINQ (in .NET 3.5) you can also do:

string id = "abc"; // etc
string value = (from row in myWorkSheetRowParameterList
where row.Id == id
select row.Value).Single();

Marc
 
J

Jon Skeet [C# MVP]

Tony Johansson said:
Assume I have the class shown below and it's stored in a generic List.
If I want to find the Value for a specific Id how do I use the find method.
We can assume that the generic List collection is named
myWorkSheetRowParameterList

public class WorkSheetRowParameter
{
public string WorkSheetRowId {get; set};
public string Id {get;set};l
public string Type {get;set};
public string Value {get;set};
public string Disabled{get;set};
public string ParameterName{get;set};
public string ParameterDuplicate{get;set};
}

It looks like you're using C# 3, so use a lambda expression:

string id = // the ID you want to find.
var found = myWorkSheetRowParameterList.Find(p => p.Id == id);
string value = found.Value;
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top