How to combine lists with respect to precedence

Viewed 61

I have a List of strings like this :

List<string> andOrList = new List<string>();
andOrList.Add("AND");
andOrList.Add("OR");
andOrList.Add("AND");

And I have 4 lists to combine :

List<int> list1 = new List<int>(new int[] { 19, 23, 29 });
List<int> list2 = new List<int>(new int[] { 1, 4, 29 });
List<int> list3 = new List<int>(new int[] { 1, 5, 23 });
List<int> list4 = new List<int>(new int[] { 2, 4, 19 });

I want to make a new list from these 4 lists using ANDs and ORs from andOrList. Since AND has higher precedence than OR first I will apply ANDs so I will have these :

   var tempList1 = list1.Intersect(list2).ToList();
   var tempList2 = list3.Intersect(list4).ToList();

And finally combine these two templists because there is an OR :

var resulList = tempList1.Union(tempList2);

As you can see it's possible to do this by hand when there is defined number of lists and defined number of ANDs and ORs. But I couldn't figure out how to do it programmatically when there are n number of Lists to combine and n-1 number of ANDs and ORs. Can you help me with that? Thanks.

2 Answers
Related