2

I'm thinkng to get a list from a linq query, but I don't knwo how. Please help.

My code is as follows, but not correct.

public List<string> SearchName(string pre)
{
    VettingDataContext dc = new VettingDataContext(_connString);
    List<string> query = (from a in dc.Accounts
                          where (a.FirstName + " " + a.LastName).StartsWith(pre)
                          select new {Name = a.FirstName + " " + a.LastName }).Distinct().ToList();
}
0

3 Answers 3

3

Try simply selecting a string value:

public List<string> SearchName(string pre)
{
    VettingDataContext dc = new VettingDataContext(_connString);
    List<string> query = (from a in dc.Accounts
                          where (a.FirstName + " " + a.LastName).StartsWith(pre)
                          select (a.FirstName + " " + a.LastName)).Distinct().ToList();
}
Sign up to request clarification or add additional context in comments.

Comments

2

It would be better to only evaluate the names once (partly because it means avoiding repeating yourself) - and to not use an anonymous type for no reason:

public List<string> SearchName(string pre)
{
    VettingDataContext dc = new VettingDataContext(_connString);
    return dc.Accounts
             .Select(a => a.FirstName + " " + a.LastName)
             .Where(name => name.StartsWith(pre))
             .Distinct()
             .ToList();
}

Note how this is one of those times where I believe it makes more sense to use the dot notation instead of query expression notation.

2 Comments

Completely agree with the dot notation point. My basic criteria is that if I find myself having to wrap a query expression in parenthesis and use dot notation on it, it's time to convert everything. If it comes down to wanting to use something that's clearer in query expression syntax, I'll write that, assign it to something, and then perform the rest of the actions on that variable.
@Shibumi: That's what I normally do, too :) I sometimes just wrap a query expression in brackets for a single method call (e.g. ToList) but if I've got more than that, it gets messy.
0

You're close. Try:

public List<string> SearchName(string pre)
{
    VettingDataContext dc = new VettingDataContext(_connString);
    List<string> query= (from a in dc.Accounts
                 where (a.FirstName + " " + a.LastName).StartsWith(pre)
                         select a.FirstName + " " + a.LastName)
                         .Distinct().ToList();
}

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.