balan
balan

Reputation: 189

Selecting items from generic list based on true condition from another list

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

Upvotes: 3

Views: 33702

Answers (3)

Meligy
Meligy

Reputation: 36594

var listResult = listData
    .Where((data, index) => listFilter[index] == 1)
    .ToList();

Reference:

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

Upvotes: 0

Yuriy Faktorovich
Yuriy Faktorovich

Reputation: 68667

var results = listData.Where((item, index) => listFilter[index] == 1);

Note that this will fail if listData is longer than listFilter, same as your code.

Upvotes: 10

Ani
Ani

Reputation: 113402

In the general case, you can do:

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

Upvotes: 4

Related Questions