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();
}
精彩评论