开发者

How to get string list from a linq query?

开发者 https://www.devze.com 2023-03-13 09:49 出处:网络
I\'m thinkng to get a list from a linq query, but I don\'t k开发者_开发问答nwo how. Please help.

I'm thinkng to get a list from a linq query, but I don't k开发者_开发问答nwo 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();
}


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();
}


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.


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();
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号