In the following procedure I load a datatable with 100 rows of data that include 5 different employee names (for the EmpName column of the dataTable). Then I use a Linq query to retrieve only rows containing 4 of the 5 names -- which I have specified which 4 names in the procedure below. Finally, I want to display a list of this query result in a datagridview. I declared var lst = ... for retrieving the EmpNames from the query ("matches"). Right now the datagridview only displays the length value (EmpName size) for each of the EmpNames in lst. But if I loop through lst (in the commented out foreach loop in the procedure below) I can see the actual EmpNames. My request is if someone could explain how I could display the EmpNames in the datagridview from lst instead of the EmpName size values.
One other request is if someone could explain if I could use the query "matches" directly as the datasource for my datagridview and skip the extra vars (mtchs, lst). I tried using "matches" directly as the datasource but got an error. So I took the extra steps (declared the additional vars -- mtchs and lst) and not getting an error anymore.
private void GetList() { var table = new DataTable(); table.Columns.Add("EmpName", typeof(string)); table.Columns.Add("col2", typeof(int)); table.Columns.Add("col3", typeof(int)); table.Columns.Add("col4", typeof(int)); table.Columns.Add("col5", typeof(int)); table.Columns.Add("col6", typeof(int)); for (int i = 0; i < 101; i++) { table.Rows.Add(GetName(i), i, i, i, i, i); } var names = new List<string> { "Jon", "Brad", "Davis", "Charlie" }; var matches = table.AsEnumerable().Where(x => names.Contains(x.Field<string>("EmpName"))); var mtchs = from Emp in matches.AsEnumerable() select Emp.Field<string>("EmpName"); var lst = new List<string>(mtchs); Console.WriteLine("EmpNames: "); //foreach (string mtch in lst) //{ // Console.WriteLine(mtch); //} datagridview1.DataSource = lst; } private string GetName(int i) { if (i % 3 == 0) return "Jon"; if (i % 5 == 0) return "Brad"; if (i % 7 == 0) return "Davis"; if (i % 13 == 0) return "Charlie"; return "Randy"; }
Rich P