简体   繁体   中英

What is the equivalent code of SQL query in C# with linq to datatable?

This is my query in T-SQL and I want to do the exact thing in C# using linq to datatable.

select
    @found = MorningIsWorking, 
    @Sh_startTime = MorningStart, 
    @Sh_endTime = MorningEnd 
from t 
where 
    t.plannum = @pn and 
    t.Date = @datepart and 
    (@timepart between MorningStart and MorningEnd)

Which MorningIsWorking is boolean, MorningStart and MorningEnd and @timepart is time and @datepart is DateTime

Edited

This is what I did but I don't know is it right or not and how to get wanted values in variables.

var res = from row in dt.AsEnumerable()
                  where row.Field<string>("plannum") == "995" &
                  row.Field<DateTime>("date") == Convert.ToDateTime("2016-08-25 10:25:00").Date &
                  Convert.ToDateTime(timepart) >= row.Field<DateTime>("MorningStart") &
                  Convert.ToDateTime(timepart) < row.Field<DateTime>("MorningEnd")
                  select row;

I believe this is the LINQ for what you are trying to accomplish, based on what information you have provided.

DateTime timepart = new DateTime(2017,2,7);
DateTime datepart = new DateTime(2016, 8, 25, 10, 25, 0);
string plannum = "995";

using (DataSet1 dt = new DataSet1())
{
     var res = from row in dt.t.AsEnumerable()
          where row.plannum == plannum &&
          row.Date == datepart &&
          timepart >= row.MorningStart &&
          timepart < row.MorningEnd
          select row;

     foreach (var row in res)
     {
          var found = row.MorningIsWorking;
          var shStartTime = row.MorningStart;
          var shEndTime = row.MorningEnd;
     }
}

Alternatively, if you are expecting only a single row to be returned, you could leave out the foreach loop as follows.

DateTime timepart = new DateTime(2017,2,7);
DateTime datepart = new DateTime(2016, 8, 25, 10, 25, 0);
string plannum = "995";

using (DataSet1 dt = new DataSet1())
{
     var res = (from row in dt.t.AsEnumerable()
          where row.plannum == plannum &&
          row.Date == datepart &&
          timepart >= row.MorningStart &&
          timepart < row.MorningEnd
          select row).Single();


     var found = res.MorningIsWorking;
     var shStartTime = res.MorningStart;
     var shEndTime = res.MorningEnd;
}

I used this Code and it Worked for me.

DataRow row = dt.AsEnumerable().FirstOrDefault
            (r => (DateTime)r["date"] == timeToCompare.Date
            & r.Field<string>("plannum") == "0995" &
            tp >= r.Field<TimeSpan>("MorningStart") &
            tp < r.Field<TimeSpan>("MorningEnd"));

And then using this to get values :

sh_starttime = row["MorningStart"].ToString();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM