Reputation: 11
OK, guys.
Firs the background! I am a retired SQL programmer who is trying to learn WPF C#.
I am taking this in small incremental steps so I can understand what I am doing. I am loading data into a WPF datagrid in the Widows_Loaded section. I eventually will use a NOT EXISTS (LINQ) statement to do that but first I just want to do a simple load.
The code is below
JR_SchoolDataDataContext conn = new JR_SchoolDataDataContext();
List<Legislator> Legislator = (from s in conn.Legislators where s.Id == 3 select s).ToList();
To start I would just like to insert the field LastName from the table Legislators. I have looked at various examples on Stackflow and other places but nothing works with the ToList.
Thanks in advance for any help.
Upvotes: 1
Views: 69
Reputation: 13976
You can do it by having the Linq expression outputting an anonymous object that contains only the LastName field.
using(JR_SchoolDataDataContext conn = new JR_SchoolDataDataContext())
{
//List<Legislator> Legislator =
var Legislator = // you really need 'var' here
(from s
in conn.Legislators
where s.Id == 3
select new { s.LastName }).ToList();
// use the List
}
After the query, Legislator
will contain a List of anonymous object instances that have a LastName
property.
Alternatively, you can do select s.LastName
end you will end up with a List<string>
:
//List<Legislator> Legislator
List<string> Legislator
= (from s
in conn.Legislators
where s.Id == 3
select s.LastName).ToList();
The first option is useful when you want to get more properties from the query and bind them, for example, to the UI later. The second is good if you only want one field.
Note that I have used the database context inside a using statement. It is a good practice to release external resources when you're done using them.
Upvotes: 1