I have this code in MS SQL:
select * from table where column1 in (select column2 from table)
How can I translate this using a DataTable?
Something along the lines of: table.select("column1 in column2")
you can't.
but you can do it via linq + table.select:
table.Select(string.Format("CITY in '{0}'",string.Join("','",table.Rows.OfType<DataRow>().Select(r=>r["COUNTRY"].ToString()).Distinct())))
EXPLANATION:
suppose you have a very simple table
ID CITY COUNTRY
1 NY USA
2 Moscow Russia
3 LA USA
4 St Peterburg Russia
Using LINQ to Objects we select all unique values from Country column and concatenate values (via string.Join) to the IN filter statement string. For our example it will be USA','Russia
surround IN filter statement with quotes via string.Format: 'USA','Russia'
Pass IN filter in dataTable.Select("CITY IN ('USA','Russia')")
FYI:
If you need to execute really cool SQL queries against DataTables\DataSets you can use NQuery it is very fast and standards compliant.
Assuming the tables are in the same DataSet, you can add a DataRelation to the DataSet and then access the child rows using GetChildRows()
var relation = new DataRelation("RelationName",
dataSet.Tables["Parent"].Columns["Column2"],
dataSet.Tables["Child"].Columns["Column1"]);
dataSet.Relations.Add(relation);
var childRows = from row in dataSet.Tables["Child"].Rows
where row.GetParentRows("RelationName").Length > 0;
You can use the following LINQ to DataSets query to get the same result as the query you have in SQL.
var rows = from r1 in table.AsEnumerable()
from r2 in table.AsEnumerable()
where r1.Field<string>("Column1") == r2.Field<string>("Column2")
select r1;
I assume from your example that the columns are coming from the same table. If not then you just need to change the table in the above as follows.
var rows = from r1 in table1.AsEnumerable()
from r2 in table2.AsEnumerable()
where r1.Field<string>("Column1") == r2.Field<string>("Column2")
select r1;
This is similar to
select * from table1 where column1 in (select column2 from table2)
Related
How to create a dynamic select query in C# using Entity Framework which will fetch all the column names from a SQL database. Here, the table names to be supplied in the query are fetched from a generic list of type IEnumerable<string>
There's a list mylist where index [0] has the table name Store, at index [1] there is a table Address and at [2] there is a table Country. Now, the query needs to be fired to database to find out what all column names are there are for Store, Address and Country table.
I assume, the final query should be put in the below manner--
select
mylist[0].1stcolumnname,
mylist[0].2ndcolumnname,
.....,
mylist[1].1stcolumnname,
mylist[1].2ndcolumnname, ....,
mylist[2].1stcolumnname,
mylist[2].2ndcolumnname,
....
from
SOMETABLENAME WITH JOINS"
If these results are fetched correctly, then final output query to be fired would look something like
Select
"Store.id", "Store.Name", "Store.gstno", "Store.addressId",
"Address.addressId", "Address.addressLine1", "Address.addressLine2",
"Address.postcode", "Address.countryId",
"Country.countryId", "Country.name"
from
SOMETABLENAME WITH JOINS;
As you can see here, each table name with each column name is fetched and the query is created.
use this one:
using (var db = new EFDemoContext())
{
var columnNames = db.Database.SqlQuery<string>(" SELECT T.name + '.' + C.name AS Name
FROM sys.objects AS T
JOIN sys.columns AS C ON T.object_id = C.object_id
JOIN sys.types AS P ON C.system_type_id = P.system_type_id
WHERE T.type_desc = 'USER_TABLE' and T.name not like N'%sysdiagrams%';").ToList();
}
I'm looking for a way to return a dynamic column list from a LINQ join of two datatables.
First, this is not a duplicate. I have already studied and discarded:
C# LINQ list select columns dynamically from a joined dataset
Creating a LINQ select from multiple tables
How to do a LINQ join that behaves exactly like a physical database inner join?
(and many others)
Here is my starting point:
public static DataTable JoinDataTables(DataTable dt1, DataTable dt2, string table1KeyField, string table2KeyField, string[] columns) {
DataTable result = ( from dataRows1 in dt1.AsEnumerable()
join dataRows2 in dt2.AsEnumerable()
on dataRows1.Field<string>(table1KeyField) equals dataRows2.Field<string>(table2KeyField)
[...I NEED HELP HERE with the SELECT....]).CopyToDataTable();
return result;
}
A few notes and requirements:
There is no database engine. The data sources are large CSV files (500K+ records) being read into c# DataTables.
Because the CSVs are large, looping through each record in the join is a bad solution for performance reasons. I've already tried record looping and it's just too slow. I get great performance on the join above, but I can't find a way to have it return just the columns I want (specified by the caller) without looping records.
If I need to loop over columns in the join, that is perfectly fine, I just don't want to loop rows.
I want to be able to pass in an array of column names and return just those columns in the resulting DataTable. If both datatables being passed in happen to have a column named the same, and if that column is in my array of column names, just pass back either column because the data will be the same between the 2 columns in that case.
If I need to pass in 2 arrays (1 for each datatable's desired columns) that's fine, but 1 array of column names would be ideal.
The column list cannot be static and hardcoded into the function. The reason is because my JoinDataTables() is called from many different places in my system in order to join a wide variety of CSVs-turned-datatables, and each CSV file has very different columns.
I don't want all columns returned in the resulting DataTable -- just the columns I specify in the columns array.
So suppose, before calling JoinDataTables(), I have the following 2 datatables:
Table: T1
T1A T1B T1C T1D
==================
10 AA H1 Foo1
11 AB H1 Foo2
12 AA H2 Foo1
13 AB H2 Foo2
Table: T2
T2A T2X T2Y T2Z
==================
12 N1 O1 Yeah1
17 N2 O2 Yeah2
18 N3 O1 Yeah1
19 N4 O2 Yeah2
Now suppose we join these 2 tables like so:
ON T1.T1A = T2.T2A
select * from [join]
and that yields this resultset:
T1A T1B T1C T1D T2A T2X T2Y T2Z
====================================
12 AA H2 Foo1 12 N1 O1 Yeah1
Notice that only 1 row is yielded by the join.
Now to the crux of my question. Suppose that for a given use case, I want to return only 4 columns from this join: T1A, T1D, T2A, and T2Y. So my resultset would then look like this:
T1A T1D T2A T2Y
==================
12 Foo1 12 O1
I'd like to be able to call my JoinDataTables function like so:
DataTable dt = JoinDataTables(dt1, dt2, "T1A", "T2A", new string[] {"T1A", "T1D", "T2A", "T2Y"});
Keeping in mind performance and the fact that I don't want to loop through records (because it's slow for large sets of data), how can this be accomplished? (The join is already working well, now I just need a correct select segment (whether via new{..} or whatever you think)).
I cannot accept a solution with a hardcoded column list inside the function. I have found examples of that approach all over SO.
Any ideas?
EDIT: I'd be ok getting ALL columns back every time, but every attempt I've made to include all columns has resulted in some kind of FULL OUTER JOIN or CROSS JOIN, returning orders of magnitude more records than it should. So, I'd be open to getting all columns back, as long as I don't get the cross join.
I'm not sure of the performance with 500k records, but here is an attempted solution.
Since you are combining two subsets of DataRows from different tables, there are no easy operations that will create the subset or create a new DataTable from the subsets (though I have an extension method for flattening an IEnumerable<anon> where anon = new { DataRow1, DataRow2, ... } from a join, it would probably be slow for you).
Instead, I pre-create an answer DataTable with the columns requested and then use LINQ to build the value arrays to be added as the rows.
public static DataTable JoinDataTables(DataTable dt1, DataTable dt2, string table1KeyField, string table2KeyField, string[] columns) {
var rtnCols1 = dt1.Columns.Cast<DataColumn>().Where(dc => columns.Contains(dc.ColumnName)).ToList();
var rc1 = rtnCols1.Select(dc => dc.ColumnName).ToList();
var rtnCols2 = dt2.Columns.Cast<DataColumn>().Where(dc => columns.Contains(dc.ColumnName) && !rc1.Contains(dc.ColumnName)).ToList();
var rc2 = rtnCols2.Select(dc => dc.ColumnName).ToList();
var work = from dataRows1 in dt1.AsEnumerable()
join dataRows2 in dt2.AsEnumerable()
on dataRows1.Field<string>(table1KeyField) equals dataRows2.Field<string>(table2KeyField)
select (from c1 in rc1 select dataRows1[c1]).Concat(from c2 in rc2 select dataRows2[c2]).ToArray();
var result = new DataTable();
foreach (var rc in rtnCols1)
result.Columns.Add(rc.ColumnName, rc.DataType);
foreach (var rc in rtnCols2)
result.Columns.Add(rc.ColumnName, rc.DataType);
foreach (var rowVals in work)
result.Rows.Add(rowVals);
return result;
}
Since you were using query syntax, I did as well, but normally I would probably do the select like so:
select rc1.Select(c1 => dataRows1[c1]).Concat(rc2.Select(c2 => dataRows2[c2])).ToArray();
Updated: It is probably worthwhile to use the column ordinals instead of the names to index into each DataRow by replacing the definitions of rc1 and rc2:
var rc1 = rtnCols1.Select(dc => dc.Ordinal).ToList();
var rc1Names = rtnCols1.Select(dc => dc.ColumnName).ToHashSet();
var rtnCols2 = dt2.Columns.Cast<DataColumn>().Where(dc => columns.Contains(dc.ColumnName) && !rc1Names.Contains(dc.ColumnName)).ToList();
var rc2 = rtnCols2.Select(dc => dc.Ordinal).ToList();
I have query like below , I tried to filter out duplicate columns by using Group BY
SELECT contacts.rowid AS ROW_PASS,
duty_rota.rowid AS ROW_PASS_ROTA,
duty_rota.duty_type AS DUTY_TYPE
FROM duty_rota,
duty_types,
contacts
WHERE duty_rota.duty_type = duty_types.duty_type
AND duty_rota.duty_officer = contacts.duty_id
AND sname IS NOT NULL
GROUP BY contacts.rowid,
duty_rota.rowid,
duty_rota.duty_type
ORDER BY duty_date
After playing with the query little bit I came to know we can't filter out distinct using group by while using ROWID. So can somebody please help me to write code (in SQL) with a logic that
if (any row is completely identical with another row of the query o/p)
{
then display only one column
}
I will be using the output as gridview's data source in C#, so if not in SQL - can you help me whether somehow in C# I can achieve to display only identical columns?
If you want to filter duplicate rows, you can use this query:
SELECT Max(duty_rota.rowid) AS ROW_PASS_ROTA,
duty_rota.duty_type AS DUTY_TYPE
FROM duty_rota,
duty_types,
contacts
WHERE duty_rota.duty_type = duty_types.duty_type
AND duty_rota.duty_officer = contacts.duty_id
AND sname IS NOT NULL
GROUP BY duty_rota.duty_type
ORDER BY DUTY_TYPE
Here you go: http://sqlfiddle.com/#!2/2a038/2
Take out the ROWID's. Example: If your table has 3 columns (colA, colB, colC) you could find exact row dups this way...
select a.* from
(
select count(*) dupCnt, colA, colB, colC from myTable
group by colA, colB, colC
) a
where dupCnt > 1
First, the ROWID is a unique field for each row, so using this field you will never have duplicates. The only solution here is to not use it. It's data does not hold anything you would want to display anyway.
Simply put, if you want no duplicates, you need the DISTINCT keyword:
SELECT DISTINCT field1,
field2
FROM table1,
table2
WHERE table1.key1 = table2.key1;
This will select all Field1, Field2 combinations from the two tables. Due to the DISTINCT keyword, each line will only be in the result list once. Duplicates will not be in the result list.
SELECT DISTINCT duty_rota.duty_type AS DUTY_TYPE
FROM duty_rota,
duty_types,
contacts
WHERE duty_rota.duty_type = duty_types.duty_type
AND duty_rota.duty_officer = contacts.duty_id
AND sname IS NOT NULL
ORDER BY duty_date
You will only need to GROUP BY if you need further operations on the result set, like counting the duplicates. If all you need is "no duplicates", the DISTINCT keyword is exactly what you are looking for.
Edit:
In case I misread your question and you want to see only those, that are duplicates, you need to group and you need to filter based on the groups criteria. You can do that using the HAVING clause. It's kind of an additional WHERE of the groups criteria:
SELECT FIELD1, FIELD2, COUNT(*)
FROM TABLE1, TABLE2
WHERE TABLE1.KEY1 = TABLE2.KEY1
GROUPB BY FIELD1, FIELD2
HAVING COUNT(*) > 1
Using the below mentioned query I am getting the all the values of a column called
promotionValue . I want to get the sum of all the values of *matched *
var matched = from table1 in dvtempPropertyRoomRatePromotion.ToTable().AsEnumerable()
join table2 in dvPropertyRooms.ToTable().AsEnumerable() on
table1.Field<DateTime>("RateDate") equals table2.Field<DateTime>("RateDate")
where table1.Field<DateTime>("RateDate") == table2.Field<DateTime>("RateDate")
select table1.Field<string>("promotionValue");
You need to parse the string to int or decimal:
var matched = from r1 in dvtempPropertyRoomRatePromotion.ToTable().AsEnumerable()
join r2 in dvPropertyRooms.ToTable().AsEnumerable()
on r1.Field<DateTime>("RateDate").Date equals r2.Field<DateTime>("RateDate").Date
select decimal.Parse(r1.Field<string>("promotionValue"));
decimal sum = matched.Sum();
Note that i've also changed some other things like the redundant where (since you've already joined these tables) or the Date property of DateTime.
Apart from that
why do you need the DataView at all? ToTable creates always a new DataTable. Why don't you use Linq-To-DataSet for all? I assume you've used the DataView for filtering, use Enumerable.Where instead. That would be more consistent, more efficient and more readable.
why is the column promotionValue a string? You should store it as a numeric type.
Here I m putting on simple query for sum of the two column of the different table.
SELECT
res.Date
,res.Cost
, res.Cost+res_con.Cost
FROM [ExpenseMst] res
inner join [ExpenseMst_2] res_con on res_con.ID =res.ID
Date | cost 1 | cost 2| total
2014-03-04 | 5200 |5200 |10400
2014-03-04 | 5012 |5012 |10024
2014-03-22 |100 |100 |200
2014-03-13 |25 |25 |50
2014-02-22 | 120 |120 |240
I hope it is useful..
:)
you can do
int sum = 0;
foreach(int match in matched)
{
sum = sum + match;
}
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