Click here to Skip to main content
15,891,033 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Hello Sir,

I have a list cities of List with "India","Delhi", "Bombay" and etc. I using Where linq over the list like,
C#
var r=cities.Where(x=>x.Length>2);

but in the r I can't see any value at all.

Please help me.

aaron
Posted
Updated 14-May-12 18:32pm
v2

I tested your example. What was the first line? In this case, it works:

C#
string[] cities = new string[] { "Dehli", "Bombay", }; // could be a list as well
var longNames = cities.Where(x => x.Length > 2); // your LINQ is correct


Both cities satisfy the condition, so, the both appear in the result longNames. Maybe, you just failed to see it? This is the iterator, so do this, for example:
C#
foreach (string name in longNames)
    System.Console.WriteLine(name);

It will print both names.

Next time, use Visual Studio Debugger, Watch (or QuickWatch) to quickly find ends.

Good luck,
—SA
 
Share this answer
 
v5
Comments
Mohammad A Rahman 14-May-12 19:29pm    
Good answer :)
Sergey Alexandrovich Kryukov 14-May-12 20:07pm    
Thank you, Mohammad.
--SA
VJ Reddy 14-May-12 20:57pm    
Good answer. 5!
Sergey Alexandrovich Kryukov 14-May-12 22:56pm    
Thank you, VJ.
--SA
In addition to Solution 1 & 2, due to the Deferred execution there is nothing in the r until we call the iterator. Please read more here[^]. And also you could read How does it work in C#? - Part 3 (C# Linq in detail)[^]

Hope it helps :)
 
Share this answer
 
Comments
(__Aaron__) 14-May-12 20:07pm    
nice link. thanks.
Sergey Alexandrovich Kryukov 14-May-12 20:08pm    
Useful piece of documentation and an interesting article referenced, a 5.
--SA
Mohammad A Rahman 14-May-12 20:11pm    
Thank you SA :)
VJ Reddy 14-May-12 20:57pm    
Good answer with useful reference. 5!
The problem is not in your LINQ statement. The following works:

C#
var list = new string[] { "India", "Delhi", "Bombay" };
var r = list.Where(x => x.Length > 2);
Console.Write("Number of cities found: " + r.Count());
 
Share this answer
 
Comments
Mohammad A Rahman 14-May-12 19:29pm    
Good answer :)
VJ Reddy 14-May-12 20:57pm    
Good answer. 5!
var r=cities.Where(x=>x.Length>2).ToList();

To do so,you can see any value .
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900