Selecting items from a general list based on true state from another list

I am wondering if there will be any solution to the LINQ / Lambda expression for the problem below.

I have 2 shared 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 out “listData” based on the true (1) criteria from “listFilter”. In the above example, I should be able to transfer data1 and data4 to a new list.

I am currently using a for loop to achieve this, as shown 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 it if someone could show me that I am using the LINQ or Lambda expression to achieve this.

thank

Balan

+3
source share
3 answers
var results = listData.Where((item, index) => listFilter[index] == 1);

Note that this will happen if listData is larger than listFilter, just like your code.

+7

:

var result = listData.Zip(listFilter, (data, filter) 
                          => new { Data = data, Filter = filter })
                     .Where(tuple => tuple.Filter == 1)
                     .Select(tuple => tuple.Data)
                     .ToList();
+4
var listResult = listData
    .Where((data, index) => listFilter[index] == 1)
    .ToList();

Link:

http://msdn.microsoft.com/en-us/library/bb548547.aspx

0
source

All Articles