微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何从linq查询中获取字符串列表?

如何解决如何从linq查询中获取字符串列表?

| 我想从linq查询获取列表,但是我不知道该怎么做。请帮忙。 我的代码如下,但不正确。
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();
}
    

解决方法

        尝试简单地选择一个字符串值:
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();
}
    ,        最好只对名称进行一次评估(部分原因是避免重复自己),并且不要无缘无故地使用匿名类型:
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();
}
请注意,这是我相信使用点表示法而不是查询表达式表示法更有意义的那些时候之一。     ,        你近了尝试:
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();
}
    

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。