LINQ Select From DataTable - c#

Just started to play around with datatable and LINQ today.
I have a datatable that gets a list of Names From SQL database.
I am looking to return a specific name from the dt using LINQ.
I have tried the following code with no success at this. Is there something that i am doing wrong with the code.
dt returns a full list of names i am just looking to reduce the names down to one name. There is a name in the adventureworks database called Blade i am trying to display this only.
DataTable dt = DAL.GetNames();
try
{
var q = from myrow in dt.AsEnumerable()
where myrow.Field<string>("Name") =="Blade"
select myrow;
dataGridView1.DataSource = q;
}
I have tried to replace the == with a .equals.
I am totally new to the concept of using a Language intergrated query.
when i run the code noting happens i dont get any errors ect just no data returned.

You're defining your query but not actually running it.
Your line:
dataGridView1.DataSource = q;
Needs to be:
dataGridView1.DataSource = q.AsDataView();

Related

ADO.NET DataTable sort does not reflect in containing DataSet

I want to sort a DataTable within a DataSet. I have the following code:
DataTable dt = ds.Tables[0];
dt.TableName = "NEWNAME";
dt.DefaultView.ApplyDefaultSort = false;
dt.DefaultView.Sort = "COL1 desc";
dt = dt.DefaultView.ToTable();
dt.AcceptChanges(); // <-- Break Point Here
ds.AcceptChanges();
As I step through the code beyond the break point in Visual Studio, checking on dt in VS visualizer shows the sorted table, but then checking on ds in VS visualiser does not show the table data in sorted order, even though the name change is reflected. I have tried multiple ways of sorting the datatable available in a google search but the outcome remains the same.
What am I doing wrong?
DefaultView.Sort doesn't sort anything. It is just a string that will be used when you require the construction of a new table like you do in the line
dt = dt.DefaultView.ToTable();
after this point the dt reference (correctly sorted with the info taken from DefaultView.Sort) is no more pointing to the ds.Tables[0]. It is an entirely new DataTable.
The other way in which the DefaultView.Sort applies is when you loop through the DefaultView like in
foreach(DataViewRow dvr in ds.Tables[0].DefaultView)
{
// Here you get a row from the table sorted according to the property.
DataRow row = dvr.Row;
.....
}

How to get particular DataTable using TableName?

One DataSet usually has lots of DataTable, but I'm only to target a particular DataTable which I thought it's pretty normal but apparently failed to do it?
Below were the approaches I've tried:
//Could not find an implementation of the query pattern for source type.......
DataTable dt = from table in changesDataSet.Tables
where table.TableName = "ABC"
select table;
//Surprisingly there was no method "Where" in changesDataSet.Tables
DataTable dt = changesDataSet.Tables.Where(x=>x.TableName="ABC").First();
Below was the code that able to print each and every table. I know I can do it via a loop but please tell me loop isn't the only options
foreach(DataTable table in changesDataSet.Tables)
{
Console.WriteLine(table.TableName);
}
You can access the table using an indexer on the collection of tables (DataTableCollection):
DataTable dt = changesDataSet.Tables["ABC"];

Return columns from identified in List<string> in linq select clause at runtime

I have looked at Dynamic linq but I am obviously missing something.
I am attempting to import files from one system to another. I have a DataTable loaded from an Excel sheet containing file information. (ExcelDataTable). I also have a HastSet of files that the user would like to import. (FilesToImport). The user selects which information he would like to import from the speadsheet, and those columns are dynamic and selected at runtime. (List VariablesToUpdate). I am joining on my ID in the query but I am not sure how to return the required columns from the datatable.
DataTable dt = new DataTable();
var query =
from excelRow in this.ExcelDataTable.AsEnumerable()
join file in this.FilesToImport.AsEnumerable()
on excelRow.Field<Guid>("ceGuid") equals file.SourceFileIdentifier
select dt.LoadDataRow(new object[]
<COMPLETELY LOST HERE>
, false);
query.CopyToDataTable();
I can work it out if I know what I would like to return using something like;
select new { ImportSourceFilePath = excelRow.Field<string>(filePathColumn)};
but like I said my columns will vary and I won't know until runtime what they are.
Any ideas?
You can use ExpandoObject for your implementation.
Here is a little tutorial for ExpandoObject
What I ended up doing;
var foundExcelRows =
from excelRow in this.ExcelDataTable.AsEnumerable()
join file in this.FilesToImport.AsEnumerable()
on excelRow.Field<Guid>("ceGuid") equals file.SourceFileIdentifier
select excelRow;
for (int i = 0; i < foundExcelRows.Count(); i++)
{
DataRow row = foundExcelRows.ElementAt(i);
// work with this row since I know the columns I expect
}

linq with dataTable in c#

I am using datatable on which I want to use Linq. but as i am new to linq i dont know how it uses.
I google it I got lots of information which is not sufficient like. If I am using datatable and i got info like :
DataRow r = from dr in ds.Tables["Customers"].AsEnumerable()
where dr.Field<Guid>("customerid").ToString() = row[2].ToString()
select dr;
dt.ImportRow(r);
and I have lots of queries like what is "dr".
dr.fields?,
".AsEnumerable()" is not present at my side.
Even this code also doesnt work:
IEnumerable<DataRow> r = from dr in ds.Tables["Customers"].Select().Where(x => x.Field<Guid>("customerid").ToString() == row[2].ToString())
select dr;
So can anyone please give me link on which i got all information from beggining on linq.
You should iterate rows to achive it
var r = ds.Tables["Customers"].Rows
.Cast<DataRow>()
.Where(r => r["fieldName"].ToString() == "Test");
Hope this can help you.
LINQ to DataSet
http://msdn.microsoft.com/en-us/library/bb386921.aspx
It's like a SQL select query, where dr is the * (that is, it is the returned data).
Some nice examples: http://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b

Querying inside a Dataset C#

I have an ADO.NET dataset which is set by a certain query,
say
SELECT ID,USER,PRODUCT,COUNT FROM PRODUCTION
Without using a where clause I need to derive some results from the dataset. Say I want to get the User and Product count of the user who has the maximum product count. (And I want to do it by using the existing dataset. I can't derive this from dataset.)
Any idea of a way to query inside the dataset? Since there are Datatables my thought was there is some way to query it.
Traditional SQL queries cannot be applied to the DataSet. The following is possible, however:
Filter rows using DataTable.Select. See here for detailed information about expressions in DataTables.
Calculate totals etc. using DataTable.Compute.
If these two don't do the trick, there's always LINQ.
Quick-and-dirty LINQ example: (which doesn't return a DataTable, but a list containing an anonymous type):
var joinedResult = dataTable1
// filtering:
.Select("MyColumn = 'value'")
// joining tables:
.Join(
dataTable2.AsEnumerable(),
row => row.Field<long>("PrimaryKeyField"),
row => row.Field<long?>("ForeignKeyField"),
// selecting a custom result:
(row1, row2) => new { AnotherColumn = row1.Field<string>("AnotherColumn") });
AsEnumerable converts a DataTable into an IEnumerable on which LINQ queries can be performed. If you are new to LINQ, check out this introduction.
Yes, you can use DataTable.Select method.
DataTable table = DataSet1.Tables["Orders"];
// Presuming the DataTable has a column named Date.
string expression;
expression = "Date > #1/1/00#";
DataRow[] foundRows;
// Use the Select method to find all rows matching the filter.
foundRows = table.Select(expression);
// Print column 0 of each returned row.
for(int i = 0; i < foundRows.Length; i ++)
{
Console.WriteLine(foundRows[i][0]);
}
Also see this link.
You can do cross-table queries of a Dataset object using LINQ to DataSet:
msdn.microsoft.com/en-us/library/bb386969.aspx

Categories

Resources