Jump to content

Filter List the data with Dictionary condition using linq


Girish Dubey

Recommended Posts

How i can filter List the data with Dictionary condition using linq.

class Person
{
	public string name
	{
		get; set;
	}

	public string subject
	{
		get; set;
	}

	public string type
	{
		get; set;
	}

	public int age
	{
		get; set;
	}
}

class Test
{
	public void FindData()
	{
		// Create dictionary and add five keys and values.
		var conditionDictionary = new Dictionary<string, string>();
		conditionDictionary.Add("subject", "english");
		conditionDictionary.Add("type", "teacher");
		
		List<Person> persons = new List<Person>();
		persons.Add(new Person
		{
			name = "Rajul",
			subject = "math",
			type = "teacher",
			age = 20
		});
		persons.Add(new Person
		{
			name = "Jhon",
			subject = "english",
			type = "teacher",
			age = 25
		});
		persons.Add(new Person
		{
			name = "Nitin",
			subject = "english",
			type = "student",
			age = 21
		});
		persons.Add(new Person
		{
			name = "Sumit",
			subject = "english",
			type = "teacher",
			age = 26
		});
		persons.Add(new Person
		{
			name = "Komal",
			subject = "science",
			type = "student",
			age = 29
		});
		
		List<Person> filteredpersons = Filter(persons, conditionDictionary);
	}

	public List<Person> Filter(List<Person> persons, Dictionary<string, string> conditionDictionary)
	{
      
      /*TODO: can you suggest how to filter list data using linq with Distionary*/
      
		var list = (from person in persons
                        from condition in conditionDictionary
                        select person).ToList();
		return list;
	}
}

 

Link to comment
Share on other sites

  • 1 year later...

Hi, Good Morning.

You wanted the list that contains the Type = "Teacher" and Subject = "English". So you can do it with the help of join linq query.

For ex:- As in your case

var list = (from person in persons 

                join condition in conditionDictionary on new{ person.subject, person.type } equals new{ condition.subject, condition.type}

               select person).ToList();

I hope this would be your answer. If any query regarding this then free to ask.

Thanks!

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...