I am wondering if there would be any LINQ/Lambda expression solution for the problem below.
I have 2 generic lists
List 1
public class Data
{
public string ID { get; set;}
public string Package { get; set;}
}
List<Data> listData = new List<Data>();
Data data1 = new Data { ID = "1", Package = "Test" };
Data data2 = new Data { ID = "2", Package = "Test2" };
Data data3 = new Data { ID = "3", Package = "Test2" };
Data data4 = new Data { ID = "4", Package = "Test4" };
listData.Add(data1);
listData.Add(data2);
listData.Add(data3);
listData.Add(data4);
List 2
List<int> listFilter = List<int>();
listFilter.Add(1);
listFilter.Add(0);
listFilter.Add(0);
listFilter.Add(1);
I would like to filter “listData” based on the true (1) criteria from “listFilter”. For the above example, I must be able to pull data1 and data4 into a new list.
At the moment, I am using a for loop to achieve this as below.
List<Data> listResult = new List<Data>();
for(int index=0; index<listData.Count; index++)
{
if(listFilter[index]==1)
{
listResult.Add(listData[index]);
}
}
I would appreciate if someone could show me to use LINQ or Lambda expression to achieve this.
Thanks
Balan
Note that this will fail if listData is longer than listFilter, same as your code.