使用linq进行多个连接

时间:2014-03-28 05:36:26

标签: c# linq datatable

这是我的疑问:

var results = from table1 in dtSplitDates.AsEnumerable()
                      join table2 in dtSplitDates.AsEnumerable() on (int)table1["FID"] equals (int)table2["FID"] into lj
                      from r in lj.DefaultIfEmpty()
                      select dtSplitDates2.LoadDataRow(new object[]
                        {
                            r["FID"],
                            r["SLNO"],
                            r == null ? string.Empty : r["Dates"]
                        }, false);

目前我正在加入专栏FID - 因此我获得了36条记录(重复):

但是为了避免重复,我还需要加入SLNO列,但我无法编写该查询 - 请帮忙。

2 个答案:

答案 0 :(得分:2)

根据我的理解,你想要两个加入条件;试试这个

   var results = from table1 in dtSplitDates.AsEnumerable()
                  join table2 in dtSplitDates.AsEnumerable() 
                  on new {id1 =(int)table1["FID"], SLno1= (int)table1["SLNO"]} 
                  equals new {id2=(int)table2["FID"], SLno2=(int)table2["SLNO"]}  into lj
                  from r in lj.DefaultIfEmpty()
                  select dtSplitDates2.LoadDataRow(new object[]
                    {
                        r["FID"],
                        r["SLNO"],
                        r == null ? string.Empty : r["Dates"]
                    }, false);

答案 1 :(得分:0)

尝试使用此示例实现:

对于多个联接:

var result=(from com in db.Company.AsEnumerable()
                    join c in db.Country.AsEnumerable() on com.CountryID equals c.CountryID
                    join s in db.State.AsEnumerable() on com.StateID equals s.StateID
                    join ct in db.City.AsEnumerable() on com.CityID equals ct.CityID
                    orderby com.Name
                    select new CompanyModel()
                     {
                         CompanyID = com.CompanyID,
                         Name = com.Name,
                         AddressLine1 = com.AddressLine1,
                         CountryID = com.CountryID,
                         StateID = com.StateID,
                         CityID = com.CityID,
                         Country = c.CountryID,
                         State = s.StateID,
                         City = ct.CityID,
                         Pin = com.Pin,
                         Phone = com.Phone,

                     }).Distinct().ToList();