How to get data between two columns in datatable?

倖福魔咒の 提交于 2019-12-12 01:36:40

问题


If i have two data tables like this :

1-penaltyrule

  ser  from-min  to-min  pen
   1     1         55     1
   2     56        90     2
   3     91        null   3

2- penaltyEmp

   ser  emp  tot-min 
    1   782   2
    2   672   67
    3   677   92
    4   56    7

I want to get the pen for each user with LINQ

i mean where tot-min BETWEEN from-min AND to-min SELECT pen

I want data table with the following result :

emp   pen
782   1
672   2
677   3
56    1

回答1:


You can use this query:

var penaltyEmps = penaltyEmp.AsEnumerable()
    .Select(r => new { ser = r.Field<int>("ser"), emp=r.Field<int>("emp"), tot_min=r.Field<int>("tot-min"), row = r });
var penaltyrules = penaltyrule.AsEnumerable()
    .Select(r => new { ser = r.Field<int>("ser"), from_min=r.Field<int>("from-min"), to_min=r.Field<int>("to-min"), row = r });

DataTable tblResult = penaltyEmps
    .Select(x => new
    {
        penaltyEmp = x,
        matchingRules = penaltyrules.Where(x2 => x.tot_min >= x2.from_min && x.tot_min <= x2.to_min)
    })
    .Where(x => x.matchingRules.Any())
    .Select(x => x.penaltyEmp.row)
    .CopyToDataTable();



回答2:


Something like this should work in LINQ for you: (Don't forget to include the System.Linq namespace).

var results = from emp in context.penaltyEmp
                  join rule in context.penaltyRule on emp.ser equals rule.ser
                  where emp.tot-min > rule.from-min && emp.tot-min < rule.to-min
                  select new { emp = emp.emp, pen = rule.pen };



回答3:


you can use this if you are using EF

   var data=(from a in db.penaltyEmp
             select new{
                  emp= a.emp,
                  pen= db.penaltyrule.Where(d=>d.from-min>a.tot-min && d.to-min==null?true:(d.to-min>a.tot-min)).Select(d=>d.pen).firstOrDefault()
                 });


来源:https://stackoverflow.com/questions/34786195/how-to-get-data-between-two-columns-in-datatable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!