1

I have a method that selects two fields from database where text in first field match some value

public static List<List<string>> SelectForSearch(string letter)
{
    var data = (from p in model.City
                where p.Name.StartsWith(letter)
                select new List<string> { p.Name, p.CountryName }).ToList();
    return data;
}

But it returns me a list like this:

[0][0]Australia
[0][1]Ballina

[1][0]Berry
[1][1]Australia

[2][0]Australia
[2][1]Bendigo
...

Country and City possition don't have a static index like this:

[0][0]Ballina
[0][1]Australia

[1][0]Berry
[1][1]Australia

[2][0]Bendigo
[2][1]Australia
...

1 Answer 1

2

Your issue is that in your select statement, instead of creating a type with Name and CountryName you are creating a List of strings. The List initialiser allows you to pass in the values when the list is constructed by placing them in { } and you are using this ability by accident, as you saw it creates a list of strings where the name is the first element and the country name is the second element. What you want to be doing is more like:

var data = (from p in model.City
            where p.Name.StartsWith(letter)
            select new { City = p.Name, CountryName = p.CountryName }).ToList();
return data;

This is using anonymous types which is not good as you want to declare a type for the return value. So you should really create a class for storage, for example:

public class CityCountryPair 
{
    public String City { get; set; }
    public String CountryName { get; set; }
}

then your method becomes

public static List<CityCountryPair> SelectForSearch(string letter)
{
    var data = (from p in model.City
                where p.Name.StartsWith(letter)
                select new CityCountryPair() { City = p.Name, 
                                               CountryName = p.CountryName 
                                              }).ToList();
    return data;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.