c# find if value exists in List c sharp

Strongly recommended book
Hi Guys,

Thought that I should share this with you.

Many times we will end up using List as our collection holder.

And that many time we wonder how to find if a value exists in List.

There are many ways you can do it. I’ll show you a couple which required less coding.

I must admit that I am not a c# pro but learning it on the go for my home made tools which requires me to get my hands dirty with c#.

Alright now lets get to the point

First we create a List.

Below is a basic List object

  1. List lt1 = new List();
  2. lt1.Add("abc");
  3. lt1.Add("def");
  4. lt1.Add("hello");
  5. lt1.Add("jas");
  6. lt1.Add("how");
  7. lt1.Add("are");
  8. lt1.Add("you");

Now lets check if value “hello” exist in lt1or not

 

  1. bool exist = lt1.Any(item => item == "hello");

I am using LINQ expression above. Above line should leave value “True” in variable “exist

Another way is using function Find on List

  1. string txt = lt1.Find(item => item == "hello");

Above line will leave txt with value hello

There are other handy methods to find value in List but I found above the most useful. One liners and does the Job nicely

I hope this helps

 

Search Terms:

Jaspreet Chahal

Self-confessed Max Payne and Howzat Cricket game addict. Big fan of Dharmendra, Keanu reeves & Lawrence "Larry" Page. I love my Wife, my son and bit of geeky stuff. I started falling in love with Blog'in last year. Writing is tending out to be fun. I write on situation I was in thus my post always travel around web development stuff. I hope you enjoy my posts.

More Posts - Website

Follow Me:
TwitterFacebookPinterestYouTube

Speak Your Mind

*

CommentLuv badge