Jalomba
Jalomba

Reputation: 25

Formatting What's returned from LINQ

So, I currently have a LINQ query

BStops.JPPlatforms.Platform
  .Where(Stop => Stop.Name.ToLower().Contains(SearchBox.Text.ToLower()))
  .Select(Stop => new { Stop.Name, Stop.PlatformNo })
  .ToList();

Query results

Which is returning the data I expect it to, the property Platform contains a list of stops that hold another class with properties I want to access to such as Name, PlatformNo and PlatforTag, now the killer for me is two things, one is less important at the moment but if you can help it would be great!

So I want to format this output so when you search it doesn't have all this garbled stuff around it, I would prefer it to be like

Annex Rd near Railway (50643)

I've tried adjusting my query to be like

BStops.JPPlatforms.Platform
  .Where(Stop => Stop.Name.ToLower().ToString().Contains(SearchBox.Text.ToLower().ToString()))
  .Select(Stop => String.Format("{0} ({1})",new { Stop.Name, Stop.PlatformNo }))
  .ToList();

But that causes it to crash back to a unhanded exception, for the life of me I can't seem to figure this out, as for the second part. I'd also like my LINQ query to search both the Name and PlatformNo properties I've already tried the logical || but it crashes back to an unhanded exception and I don't know enough about LINQ to figure out why, any help at this point would be great :).

Upvotes: 0

Views: 1384

Answers (2)

Richard Schneider
Richard Schneider

Reputation: 35477

The Where clause is not performant. The Text.ToLower should be done outside of the Linq. Also ToLower returns a string, so there is no need go call ToString

The Select should not create a new object.

var text = SearchBox.Text.ToLower();
BStops.JPPlatforms.Platform
  .Where(stop => stop.Name.ToLower().Contains(text))
  .Select(stop => String.Format("{0} ({1})", stop.Name, stop.PlatformNo))
  .ToList();

Upvotes: 0

Chetan
Chetan

Reputation: 6891

Changing your LINQ query to this would solve the problem.

BStops.JPPlatforms.Platform.Where(Stop => Stop.Name.ToLower()
                                                   .Contains(SearchBox.Text.ToLower()))
                           .Select(Stop => new 
                                           { 
                                               StopAddress = $"{Stop.Name} {Stop.PlatformNo}" 
                                           })
                           .ToList();

Upvotes: 1

Related Questions