2011-07-06 48 views
0

我有幾個需要查詢的數據集。使用LINQ,我結束了這樣的代碼..使用LINQ做數據集的複雜查詢

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... 
}; 

必須有一個更簡單的方法來做到這一點。有沒有辦法用SQL語句查詢數據集?

回答

2

可以簡化WHERE部分:

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")) 

也許你可以重構SELECT部分​​成一個構造(未匿名類型)。

但是,不能,你不能將SQL應用於數據集(超出你已經用LINQ做的)。

考慮使用像Entity框架這樣的ORM,這會讓生活變得更容易。