LINQ – filtering data structures

Using Language-Integrated Query (LINQ) has become very common in recent years as it is an easy way to retrieve data from various data structures eg. arrays. The code itself is also very clean and much shorter comparing to non LINQ implementations.

In this article I will show you how easy filtering data can be using LINQ.

Lets create client class first.

public class Client
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public IEnumerable
Addresses { get; set; } } public class Address { public string Street { get; set; } public string City { get; set; } public string Country { get; set; } }

Next we create Client data source with some dummy data

 public IEnumerable ClientDB
{
    get
    {
        var clients = new List();

        #region load dummy data
        clients.Add(new Client()
        {
            ID = 1,
            Name = "Client1",
            Addresses = new List
() { new Address() { Street = “street1”, City = “city1”, Country = “UK” }, new Address() { Street = “street2”, City = “city2”, Country = “US” } } }); clients.Add(new Client() { ID = 2, Name = “Client2”, Addresses = new List
() { new Address() { Street = “street1”, City = “city1”, Country = “IT” }, new Address() { Street = “street2”, City = “city2”, Country = “US” } } }); clients.Add(new Client() { ID = 3, Name = “Client3”, Addresses = new List
() { new Address() { Street = “street1”, City = “city1”, Country = “ES” }, new Address() { Street = “street2”, City = “city2”, Country = “US” } } }); #endregion return clients; } }

Now we can filter data from our structure before we can display it on the gridview. We only want to display clients with the UK address.

   
protected void Page_Load(object sender, EventArgs e)
    {
        var clients_With_UK_AddressOnly = ClientDB;

        //lets filter data
        clients_With_UK_AddressOnly = from client in ClientDB
                                        where client.Addresses.Count(a => a.Country == "UK") > 0
                                        select client;

        //or you can do it shorter using "Any" function
        clients_With_UK_AddressOnly = ClientDB.Where(c => c.Addresses.Any(a => a.Country == "UK"));

        GridView1.DataSource = clients_With_UK_AddressOnly;
        GridView1.DataBind();
    }

As you can see when using LINQ, we can do a lot with the data in just one line of code. The code itself if less prone to errors and more elegant.

LINQ-data-filtering

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading...Loading...