sansactions
sansactions

Reputation: 243

splitting List<Object> based on the value of a variable in that Object

I am trying to split my list into multiple smaller lists but don't know how i should do it.

List<Object> list = new List<Object>();

This is my original list that contains the object Object. I am trying to split this list based on the variables of this Object.

example:

public class Object {
   string var1;
   int var2;
   int var3;
}

lets say the list Object has 3 possible var1 ("yes","no","maybe") then i want 3 Lists where each list are all the objects that have "yes","no" or "maybe" as var1 (this can be a list of 100 objects long with each object being one of this string) (the amount of possibilities in var1 is not constant)

Upvotes: 2

Views: 3371

Answers (4)

IEssing
IEssing

Reputation: 9

            List<Object> list1 = new List<Object>();
            List<Object> list2 = new List<Object>();

            for (int i=0;i<list.Count;i++)
            {
                if (list.var1 == 0)
                {
                    list1.Add(list[i]);
                }
                if (list.var1 == 1)
                {
                    list2.Add(list[i]);
                }

            }

Upvotes: 0

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186728

Have a look at ILookup:

var splitted = list.ToLookup(item => item.var1);

Upvotes: 2

Deepak Sharma
Deepak Sharma

Reputation: 4170

Here you will have splitted list of your object. you can use group by your property of your class. something like.

var splittedList = list.GroupBy(c=>c.var1).Select(c => c.ToList()).ToList() ;

Here splittedList is type of List<List<YourObject>> So for your Yes, No, MayBe case it will return list of 3 List. and each of these three will contains object with same var1 property

Upvotes: 4

Jamadan
Jamadan

Reputation: 2313

Use System.Linq:

List<Object> listYes = list.Where(o => o.var1 == "yes").ToList();
List<Object> listNo = list.Where(o => o.var1 == "no").ToList();
List<Object> listMaybe = list.Where(o => o.var1 == "maybe").ToList();

This will give you 3 lists of objects where var1 equals the respective valuein the Where() clause.

Upvotes: 1

Related Questions