CodeCopy

November 5, 2009

How to remove objects from generic List by property value

Filed under: c# — sterndorff @ 23:59
Tags: , ,

Having two generic lists of type List<MyClass>, how do I remove from List1 all the instances of List2, matching a property?

This is the setup. I have a class:

public class MyClass
{
    public int MyValue { get; set; }
    public int MyOtherValue { get; set; }
}

And two lists:

List<MyClass> list1 = new List<MyClass>();
list1.Add(new MyClass() { MyValue = 1, MyOtherValue = 10 });
list1.Add(new MyClass() { MyValue = 2, MyOtherValue = 20 });
list1.Add(new MyClass() { MyValue = 3, MyOtherValue = 30 });
list1.Add(new MyClass() { MyValue = 4, MyOtherValue = 40 });

List<MyClass> list2 = new List<MyClass>();
list2.Add(new MyClass() { MyValue = 2, MyOtherValue = 50 });
list2.Add(new MyClass() { MyValue = 3, MyOtherValue = 60 });

I want to remove all list2 instances from list1 matching on MyValue property.

(more…)

September 28, 2009

Find index in list of objects

Filed under: c# — sterndorff @ 17:27
Tags: , ,

If you have an object in a list of these objects, you can find the index of the list by:

int index = listOfObjects.IndexOf(testObject);

But that only goes if the testObject reference is in the listOfObjects. If the object is not in the list, but you want to find the index based on a property, do this:

List<myObject> listOfObjects = new List<myObject>();
listOfObjects.Add(new myObject() { Name = "obj 1" });
listOfObjects.Add(new myObject() { Name = "obj 2" });

myObject testObject = new myObject() { Name= "obj 1"};

int index = listOfObjects.Select((s, i) => new { S = s, Index = i }).Where(i => i.S.Name == testObject.Name).First().Index;

Of cause you have to be shure that the testObject is in the list or you will get a exception.

September 18, 2009

“Casting” list to observablecollection

Filed under: c#,wpf — sterndorff @ 11:04
Tags: , , ,

Easy as pie without for loops:

List<string> myList = new List<string>();
ObservableCollection<string> myObs = new ObservableCollection<string>();

myList.ForEach(i => myObs.Add(i));

Theme: Rubric. Blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.