Guys, are you familiar with LINQ? . If
not I will suggest you to study some good tutorial of LINQ. What exactly it
does. And if you are already done some work on LINQ and randomly clicking
various article to know some extra knowledge .NET or basically programming
languages then this post is suitable for you. Talking too much??
Ok, let’s come to point. Here I will
show how to search particular item from a collection. Here I have created a
collection of object of my person class. For sake of simplicity I have kept
only two object of my class.
And in List collection I have created
two object of my Person class. Now using LINQ I want to find some item from my
collection. Here the query
var hasName = (from NameList in list
where NameList.Name
== "Sourav"
select
NameList).Any();
will find whether “Sourav” is present
is not in name property in collection of object. If present then it will return
true. Let’s see below code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Data;
using System.Diagnostics;
using System.Data.SqlClient;
using System.Collections.Generic;
namespace BlogProject
{
class Person
{
public string Name { get; set; }
public string Surname { get; set; }
}
class Program
{
static void Main(string[] args)
{
IList<Person> list = new List<Person>();
Person p = new Person();
p.Name = "Sourav";
p.Surname = "Kayal";
list.Add(p);
p = new Person();
p.Name = "Prasanta";
p.Surname = "Kayal";
list.Add(p);
//Search in list to check wheather
sourav is present or not
var hasName = (from
NameList in list
where NameList.Name
== "Sourav"
select
NameList).Any();
if (hasName)
{
Console.Write("Name is
present in list");
}
else
Console.Write("Name not
present");
Console.ReadLine();
}
}
}
No comments:
Post a Comment