Debugmode
Debugmode

Reputation: 93

How to Get results from multiple tables using LINQ

I am working on autocomplete textbox. In this user can type their city name and from this input i want to search records from database table and display related combination list of city name, state name and country name.

How can i get this details using LINQ.

I have my table structure as below,

Country Countryid PK CountryName

State Stateid PK StateName Countryid FK

City Cityid PK CityName Stateid FK

I want to get result on autocomplete textbox.

E.g if user writes san he will get list of city name contains san

like San Francisco, California, United States of America.

How can i write LINQ query to get this result.

Upvotes: 0

Views: 898

Answers (3)

marko
marko

Reputation: 2831

Another variant:

var matches = cities.Where(c => c.CityName.Contains(substr))
                    .Select(a => String.Format("{0} {1} {2}",
                                        a.CityName, 
                                        a.State.StateName, 
                                        a.State.Country.CountryName 
                           ));

Upvotes: 1

Icarus
Icarus

Reputation: 63970

var query = from c in dataContext.City
            where c.Contains(keyword)
            select c.CityName + ", " + c.State.StateName+ ", "+ c.State.Country.CountryName;

Upvotes: 1

Anders Abel
Anders Abel

Reputation: 69280

Using linq-to-sql:

var q = from c in context.cities
select c.CityName + ", " + c.State.StateName + ", " + c.State.Country.CountryName
where CityName.StartsWith(typed);

This will give an IEnumerable with the suggestions that matches the typed characters.

Upvotes: 1

Related Questions