Friday, June 05, 2009

Filter one list using another list in LINQ

public class Country
{
public string CountryID { get; set; }
public string CountryVal { get; set; }
public string CountryDesc { get; set; }


}



List<Country> sourceCountry = new List<Country>
{
new Country{ CountryID="1" , CountryVal="IND", CountryDesc="India"},
new Country{ CountryID="2" , CountryVal="USA", CountryDesc="America"},
new Country{ CountryID="3" , CountryVal="UK", CountryDesc="London"},
new Country{ CountryID="4" , CountryVal="PAR", CountryDesc="Paris"}
};

List<Country> filterCountry = new List<Country>
{
new Country{ CountryDesc="India"},
new Country{ CountryDesc="London"}

};


var finalcountry = from item in sourceCountry
from some in filterCountry
where item.CountryDesc == some.CountryDesc
select item;

List<Country> fin = finalcountry.ToList<Country>();

Let Keyword in C#

Let’s see how the “let” keyword works.

I will start from a list of numbers stored as strings.
I would like to get only numbers greater than 10 and order them by their value but keeping the result as an enumeration of string.

We can write it quickly this way:

var values = new string[] { "12", "4", "7", "18", "32" };
var q =
from s in values
where Convert.ToInt32(s) > 10
orderby Convert.ToInt32(s)
select s;
This works fine but we all notice the ugly “Convert.ToInt32(s)” used twice on the same value. Thanks to the “let” keyword we can create a new parameter that will be accessible in all the query.

var values = new string[] { "12", "4", "7", "18", "32" };
var q =
from s in values
let i = Convert.ToInt32(s)
where i > 10
orderby i
select s;