Using LINQ to do complicated queries with datasets
I have s开发者_如何学JAVAeveral datasets that I need to query. Using linq, I end up with code like this..
var query =
from table1 in table_1.AsEnumerable()
join table2 in table_2.AsEnumerable()
on table1.Field<string>("Value1") equals
table2.Field<string>("value2") into join1
from joinData in join1.AsEnumerable()
join table1_1 in table_1.AsEnumerable()
on joinData.Field<string>("Value3") equals
table1_1.Field<string>("Value1")
into join2
from joinData2 in join2.AsEnumerable()
where joinData2.Field<string>("Value4") == "1" ||
joinData2.Field<string>("Value4") == "2" ||
joinData2.Field<string>("Value4") == "3" ||
joinData2.Field<string>("Value4") == "4" ||
joinData2.Field<string>("Value4") == "5" ||
joinData2.Field<string>("Value4") == "6" ||
joinData2.Field<string>("Value4") == "7" ||
joinData2.Field<string>("Value4") == "8"
select new
{
Value1 = data1.Field<string>("Value1"),
Value2 = data1.Field<string>("Value2"),
Value3 = data1.Field<string>("Value3"),
Value4 = data1.Field<string>("Value4"),
Value5 = data1.Field<string>("Value5"),
Value6 = data1.Field<string>("Value6"),
Value7 = data1.Field<string>("Value7"),
Value8 = data1.Field<string>("Value8"),
Value9 = data1.Field<string>("Value9"),
Value10 = data1.Field<string>("Value10"),
Value11 = data1.Field<string>("Value11"),
Value12 = data1.Field<string>("Value12"),
etc...
};
There has to be an easier way to do this. Is there any way to just query a dataset with an SQL statement?
You can simplify the WHERE part:
where joinData2.Field<string>("Value4") == "1" ||
joinData2.Field<string>("Value4") == "2" ||
joinData2.Field<string>("Value4") == "3" ||
where List<string>{ "1", "2", "3", ... }
.Contains( joinData2.Field<string>("Value4"))
And maybe you could refactor the SELECT part into a constructor (of a not-anonymous type).
But no, you cannot apply SQL to datasets (beyond what you're already doing with LINQ).
Consider using an ORM like Entity framework, that would make life a lot easier.
精彩评论