How to get a column value from a data table object. I have the id column on which basis I am trying to get another column value.
e.g. ApplicationId is the primary key column which I have and now I want to get the xyz column value for this ApplicationId.
I have accomplished my result by making use of the following Linq statement
List<string> lstResult= (from table in dt.AsEnumerable()
where table.Field<int>("Id") == id
select table.Field<string>("status")).ToList();
string dtStatus = lstResult[0];
you can do it lik this
var results = (from rows in dt.AsEnumerable() select new {resultcolumnname=row["resultcolumnname"]}).where(item=>item.columnname == value).ToList()
var x= from myrow in myDataTable.asEnumerable() where myrow.ApplicationId==[YourValue] select myRow.[ColumnYouWant];
I am not great when it comes to linq but this should do the trick.
Related
I am binding ComboBox using LINQ Join query. Below is my code:
var list = (from a in context.tbl_Products
join c in context.tbl_CurrentStock on a.ProductID equals c.ProductID
where c.Qty > 0
select new
{
ProductID = a.ProductID,
ProductName = a.ProductName
}).ToList();
cmbProduct.DataSource = list;
cmbProduct.ValueMember = "ProductID";
cmbProduct.DisplayMember = "ProductName";
cmbProduct.SelectedIndex = -1;
Table Details:
tbl_Products : ProductID, Product Name
Data in table
1,ABC
2,BCA
3,CDA
tbl_CurrentStock: StockID,ProductID,Qty
Data in table:
1,1,5
2,2,10
3,3,50
I am using cmbProduct.SelectedValue like below:
int ProductID = Convert.ToInt32(cmbProduct.SelectedValue);
var Product = context.tbl_Products.Single(o => o.ProductID == ProductID);
Until here it is fine. In combobox I have selected "ABC", but I am getting cmbProduct.selectedvalue value as 2 instead of 1. Same way if I select 2nd product getting value as 3 instead of 2, it is not giving selected value, instead it is giving first value in the list. What could be the problem? It's silly and eating my head. This is working fine, when I don't use JOIN Query (if I bind data from only one table)
Thanks in Advance
Problem resolved after changing sorted property of combobox to false. Combobox is sorting the productnames but not product IDs. This was causing issue. –
I have a DataTable, with two columns of type String named ID and Value. These values are not required to be unique.
As I add to my DataTable throughout my application, at some point I am trying to get the last item that was added that meets the value of the two properties. For example, for all records where ID = 1 and Value = 2, there may be several. I need the last record.
I have been trying to use LINQ groupbys, the MyDataTable variable is my datatable.:
var groupQuery = from table in MyDataTable.AsEnumerable()
group table by new {column1 = table["PERSON_GU"], column2 = table["FIELD"]}
into groupedTable
select new
{
x = groupedTable.Key, // Each Key contains column1 and column2
y = groupedTable.Count()
};
I cant figure out how to make this select last though, it appears to return an anonymous type which is a little out of my development skill wheelhouse.
In summary, I have a datatable with two columns, I am trying to group my final datatable by these column values, and then get the last item.
If you want the last DataRow of each group:
var groupQuery =
from table in MyDataTable.AsEnumerable()
group table by new {column1 = table["PERSON_GU"], column2 = table["FIELD"]}
into groupedTable
select groupedTable.Last();
CREATE TABLE [MyNames]
(
[ID] INT IDENTITY PRIMARY KEY,
[Name] NVARCHAR(255) NULL
)
INSERT INTO [MyNames] VALUES ('John')
INSERT INTO [MyNames] VALUES ('Jane')
INSERT INTO [MyNames] VALUES ('Peter')
INSERT INTO [MyNames] VALUES ('Montgomery')
INSERT INTO [MyNames] VALUES ('Sarah')
Based on the above (hypothetical) SQL schema and data, I want to use Linq to SQL to get all results where the name is in values of an array.
string[] names = {"John", "Cassandra", "Sarah"};
var results = (from n in db.Names
where n.Name **in names**
select n).ToList();
The results should include John and Sarah. With that information I am then able to add the entries that need to be added, in this case Cassandra.
I don't want to load all the Names because the list can get exceptionally long.
You can use names.Contains():
string[] names = {"John", "Cassandra", "Sarah"};
var results = (from n in db.Names
where names.Contains(n.Name)
select n).ToList();
You can use the Contains extension method:
var results = (from n in db.Names
where names.Contains(n.Name)
select n).ToList();
var results = (from n in db.Names
where names.Any(x=>x == n.Name)
select n).ToList();
I am using a Linq query to groupBy a column name and return a list of rows.
var query = from row in ProcessSummaryData.AsEnumerable()
group row by new { Key = row .Field<string>("GroupDescription") } into g
select new
{
GroupDescription = g.Key,
Values = g.ToList(),
};
The output of this query is something like this
GroupDescription Values
1 12,abc,xyz
12,abx,yut
13,tye,lki
2 14,asd,acd
Now the in the above example Values is a DataRow and I have just given an example of values in it.
Now what I want is that for GroupDescription '1' the output only has one row with '12' value.
I have tried a few things one of which is to have another Linq query on first list but that's over complicating things.
How do I use linq to group by first column and then use Distinct on certain column returned list to get only Distinct rows?
To get the first occurrence of a field's values you can group by that field and then take the first row of each grouping.
var query = from row in ProcessSummaryData.AsEnumerable()
group row by new { Key = row .Field<string>("GroupDescription") } into g
select new
{
GroupDescription = g.Key,
Values = (from value in g.ToList()
group value by value["Id"] into valueGroup
select valueGroup.First()).ToList()
};
How can i merge two Datatables into the same row. I am using different stored procedures to get data into datasets. In asp.net using c#, i want to merge them so there are same number of rows as table 1 with an added column from table 2.
For example:
DataTable table1 = dsnew.Tables[0];
DataTable table2 = dsSpotsLeft.Tables[0];
table1.Merge(table2);
This is fetching me 4 rows instead of 2 rows. What am i missing here? Thanks in advance!!
You cannot use the method Merge in this case, instead you should create new DataTable dt3, and then add columns and rows based on the table 1 and 2:
var dt3 = new DataTable();
var columns = dt1.Columns.Cast<DataColumn>()
.Concat(dt2.Columns.Cast<DataColumn>());
foreach (var column in columns)
{
dt3.Columns.Add(column.ColumnName, column.DataType);
}
//TODO Check if dt2 has more rows than dt1...
for (int i = 0; i < dt1.Rows.Count; i++)
{
var row = dt3.NewRow();
row.ItemArray = dt1.Rows[i].ItemArray
.Concat(dt2.Rows[i].ItemArray).ToArray();
dt3.Rows.Add(row);
}
Without knowing more about the design of these tables, some of this is speculation.
What it sounds like you want to perform is a JOIN. For example, if you have one table that looks like:
StateId, StateName
and another table that looks like
EmployeeId, EmployeeName, StateId
and you want to end up with a result set that looks like
EmployeeId, EmployeeName, StateId, StateName
You would perform the following query:
SELECT Employee.EmployeeId, Employee.EmployeeName, Employee.StateId, State.StateName
FROM Employee
INNER JOIN State ON Employee.StateId = State.StateId
This gives you a resultset but doesn't update any data. Again, speculating on your dataset, I'm assuming that your version of the Employee table might look like the resultset:
EmployeeId, EmployeeName, StateId, StateName
but with StateName in need of being populated. In this case, you could write the query:
UPDATE Employee
SET Employee.StateName = State.StateName
FROM Employee
INNER JOIN State ON Employee.StateId = State.StateId
Tested in SQL Server.
Assuming you have table Category and Product related by CategoryID, then try this
var joined = from p in prod.AsEnumerable()
join c in categ.AsEnumerable()
on p["categid"] equals c["categid"]
select new
{
ProductName = p["prodname"],
Category = c["name"]
};
var myjoined = joined.ToList();
Sources
LINQ query on a DataTable
Inner join of DataTables in C#
http://social.msdn.microsoft.com/Forums/en-US/adodotnetdataset/thread/ecb6a83d-b9b0-4e64-8107-1ca8757fe58c/
That was a LINQ solution. You can also loop through the first datatable and add columns from the second datatable