Alex Rivera | Logout

Filter List<> object without using foreach loop in C#2.0

Asked 2009-05-22T11:47:12.137
9

How we can filter the object in List<> in C#?

Edit
Report

2 Answers

18

Let's say we have a List<string> and you want only the items where the length of the string is greater than 5.

The code below will return a List<string> with the results:

List<string> myList = new List<string>();
myList.Add("hello");
myList.Add("world!");
myList.Add("one");
myList.Add("large!!");
List<string> resultList = myList.FindAll(delegate(string s) { return s.Length > 5; });

resultList will containt 'world!' and 'large!!'. This example uses an anonymous method. It can also be written as:

List<string> myList = new List<string>();
// ..
List<string> resultList = myList.FindAll(OnlyLargerThanFive);

//..

private static bool OnlyLargerThanFive(string s)
{
  return s.Length > 5;
}

The delegate above, OnlyLargerThanFive, is also called a Predicate.

answered 2009-05-22T11:51:05.017
3

List<>.Find (gives the first matching occurence) and List.FindAll() gives all matching occurences. An example with a list of complex types would is as follow:

I have a class Report:

public class Report
{
    public string ReportName;
    public ReportColumnList ReportColumnList;
}

and a list of Report

List<Report> reportList;

To find items in the list where ReportName = 'MyReport', the code would be:

string reportName = "MyReport";
List<Report> myReports = reportList.FindAll(delegate(Report obj) { return obj.ReportName == reportName; });

To get the first report:

Report rc = reportList.Find(delegate(Report obj) { return obj.ReportName == reportName; });

Note that the object passed to the delegate should be of the type with which the list is populated.

answered 2009-05-22T12:09:44.197

Your Answer