Linq syntax instead of for each

Posted by Laghaterohan under C# on 7/9/2013 | Points: 10 | Views : 12384 | Status : [Member] | Replies : 4
Hi,

I want to check a particular role by looping through an array. if the role matches then I set the value to true else I return false. This I am doing by using foreach loop, instead I want to use LINQ. how to do it?

eg.
foreach( var role in Roles)
{
if ( role == "student")
{
isStudent = true;
return isStudent;
}
}


Instead of using foreach above I would like to use LINQ, how to use it?

Best Regards,
Rohan Laghate



Responses

Posted by: Ssj_Kumar on: 7/9/2013 [Member] Starter | Points: 25

Up
0
Down
if(Roles.Where(x=>x.role=="student").Count()>1)
{
isStudent = true;
return isStudent;
}

Regards,
Jayakumar Selvakani

Laghaterohan, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Laghaterohan on: 7/10/2013 [Member] Starter | Points: 25

Up
0
Down
Hi,
Thanks for your reply.

Could you please also let me know what linq syntax to use just to loop through the collection instead of using foreach.

eg. foreach(var a in collection)
{
}

so here above instead of using foreach how can I use Linq.

Many Thanks once again.

Best Regards,
Rohan Laghate

Laghaterohan, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Ssj_Kumar on: 7/10/2013 [Member] Starter | Points: 25

Up
0
Down
Sorry Rohan, I can't understand your requirement, Linq and foreach both are not same, as of my knowledge we can filter the data or modify the data using linq
give me the clear requirement will provide you the solution

Regards,
Jayakumar Selvakani

Laghaterohan, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Venkat0454 on: 7/13/2013 [Member] Starter | Points: 25

Up
0
Down
var Roles = new String[] { "student", "ddd" };

if (Roles.Where(x => x == "student").Count() > 1)
{
isStudent = true;

}


Laghaterohan, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response