I am running C# framework 2.0 and I would like to get some of the data from a list? The list is a List<>. How can I do that without looping and doing comparaison manually on each element of the List<>?
If I follow your question correctly, you can just call the Find()
or FindAll()
methods to get data items out of the list. For example:
List<string> myList = ..;
List<string> startingWithA = myList.FindAll(delegate(string s) { return s.StartsWith("A"); });
You can try Predicate. Here is a code I wrote to illustrate the point. Of course, as you can see in this example, you can move the Predicate outside the calling class and have a control on it. This is useful if you need to have more option with it. Inside the predicate you can do many comparison with all property/function of your object.
static void Main()
{
List<SimpleObject> list = new List<SimpleObject>();
list.Add(new SimpleObject(1,"Jon"));
list.Add(new SimpleObject( 2, "Mr Skeet" ));
list.Add(new SimpleObject( 3,"Miss Skeet" ));
Predicate<SimpleObject> yourFilterCriteria = delegate(SimpleObject simpleObject)
{
return simpleObject.Name.Contains("Skeet");
};
list = list.FindAll(yourFilterCriteria);//Get only name that has Skeet : Here is the magic
foreach (SimpleObject o in list)
{
Console.WriteLine(o);
}
Console.Read();
}
public class SimpleObject
{
public int Id;
public string Name;
public SimpleObject(int id, string name)
{
this.Id=id;
this.Name=name;
}
public override string ToString()
{
return string.Format("{0} : {1}",Id, Name);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With