In this article I will show you how you can use Any Method
of LINQ in c#.net. In this I have used a list to perform the Any operation.
Some of my previous articles are as follows: Date
Time Formatting in C#, Group
CheckBox In C# WinForm, DropdownList
AutoPostback Functionality In MVC Using C#.Net, How
to Find Gridview Control on Button Click in Asp.Net C#, How
To Move All Items From One Listbox To Another In C#, Read
Outlook Inbox Mail And Email Count Of Inbox Using C#.Net, Code
to Convert or Writing DataSet Contents Into An XML Data File Using C#.Net In
Asp.Net.
So for this article first I have created a list and then applied any function. So What exactly Linq Any function do.
So for this article first I have created a list and then applied any function. So What exactly Linq Any function do.
Any receives an argument of a proposition. It determines if
any element in a collection matches with in a collection then only it returns
the result otherwise it will not return any output. We can also perform this
operation by using loop. But when we use look code size will get increased and
it will become complex.
Now here is the code example.
using System;
using
System.Collections.Generic;
using System.Linq;
using System.Text;
using
System.Threading.Tasks;
namespace
ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
List<State> objState = new List<State>();
objState = GetStateData().Where(s => s.CityList.Any(m => m.Id ==
3)).ToList();
}
public static List<State>
GetStateData()
{
List<State> objState = new List<State>();
List<City> objCity1 = new List<City>();
objCity1.Add(new City { Id = 1, CityName = "City
11" });
objCity1.Add(new City { Id = 2, CityName = "City
12" });
objState.Add(new State { Id = 1, StateName = "State
1", CityList = objCity1 });
List<City> objCity2 = new List<City>();
objCity2.Add(new City { Id = 1, CityName = "City
11" });
objCity2.Add(new City { Id = 3, CityName = "City
22" });
objState.Add(new State { Id = 2, StateName = "State
2", CityList = objCity2 });
return objState;
}
}
public class State
{
public int Id { get; set; }
public string StateName { get; set; }
public List<City> CityList { get; set; }
}
public class City
{
public int Id { get; set; }
public string CityName { get; set; }
}
}
|
In above code I have create a city state collection. So when
we try to get the record on that case we need to apply where clause on a
collection inside a collection. Which is not possible. So we use Any for this.
Now First I will show what you get by passing city id 1:
Here you are getting both the record because the city is 1
exists in both the states.
Now when we pass the city id 3 on that case we are getting
only one state value. Have a look of the output.
Thanks for this explanation. It was really helpful.
ReplyDelete3d rendering services