tags:

views:

151

answers:

6

I have a List<> in my program, filled with my custom class. I want to be able to extract an object from the list by simply specifying an integer, then returning all objects that have an integer property set to that integer. I was thinking of doing it like this:

int exampleint = 5;
List<MyClass> extract = new List<MyClass>();
for(int i = 0; i < list.Length; i++) {
    if(list[i].Number == exampleint)
        extract.Add(list[i]);
}
return extract;

Is there any better or faster way do do this? Just wondering.

Update: Chris, your answer was a little off. This:

 List<MyClass> extract = list.FindAll(delegate(int obj) { return obj.Number == exampleint; });

should in fact be this:

List<MyClass> extract = list.FindAll(new Predicate<MyClass>(delegate(MyClass obj) { return obj.Number == exampleint; }));

Your first example gave me errors. But thanks for pointing me in the right direction, it seems to work now.

A: 

If you're using C# 3:

return (from e in list
        where e.Number == exampleint
        select e).ToList();

This will run a LINQ query that pulls them out, then converts to a list. If you can return IEnumerable instead, you can avoid the ToList() call.

Reed Copsey
A: 

Use Linq/extension methods:

var result = list.Where(x => x.PropertyValue == YourSelectedValue);
Konrad Rudolph
A: 

If you can use Linq:

List extract = existingList.Where(x => x.Number == exampleInt).ToList();

Chris Holmes
+6  A: 
List<MyClass> extract = list.FindAll(obj => obj.Number == exampleint);

OR (if you're using .NET 2.0 and can't use expressions)

List<MyClass> extract = list.FindAll(delegate(MyClass obj) { return obj.Number == exampleint; });
Chris Doggett
+! That's more elegant than mine :) I always forget about FindAll.
Reed Copsey
Thank you! I'm using 2.0, probably should have said that.
Bevin
obj should be a MyClass
configurator
configurator is correct. For the first example, .NET will auto-detect the type, but the second one should've been MyClass.
Chris Doggett
+1  A: 

If you only have C#2, try this:

public delegate bool Predicate<T>(T item);

public static IEnumerable<T> Where(IEnumerable<T> source, Predicate pred)
{
    foreach (T item in source)
    {
        if (pred(item))
            yield return item;
    }
}

You can reuse that whenever you have this kind of filtering requirement, like this:

IEnumerable<MyClass> filtered = Where(list, delegate(MyClass c) { return c.Number == exampleint; });

It's essentially identical to the Linq solutions and it will enable you to get use to this style of list processing ready for when you can upgrade your compiler.

Daniel Earwicker
+1  A: 

You can use linq.