Inner Join两个数据表使用Linq而不与另一个表有关系

时间:2016-02-18 08:38:36

标签: linq c#-4.0 linq-to-sql datatable

我想加入两个p_seg <- xyplot(lci ~ cond1 | cond2, data = summary_data, ylim = c(1, 13), panel = function(...) { # lower and upper y values y0 <- list(summary_data$lci[c(1, 3)], summary_data$lci[c(2, 4)]) y1 <- list(summary_data$uci[c(1, 3)], summary_data$uci[c(2, 4)]) # insert vertical lines depending on current panel panel.segments(x0 = 1:2, x1 = 1:2, y0 = y0[[panel.number()]], y1 = y1[[panel.number()]]) }) p_comb <- subject_stripplot + as.layer(p_seg) # print(p_comb) 之类的

datatable

注意:没有像table1.id = table2.id

这样的关系

我有select * from table1 Inner join table2 on table2.id in (1,2,3) 代码,但不知道如何提出Linq请帮助

condition

我上面没有var JoinResult = (from p in table1 .AsEnumerable() join t in table2 .AsEnumerable() on p.Field<int>("id") equals t.Field<int>("id") select new { ID = p.Field<int>("ID") }).ToList(); 关系。

4 个答案:

答案 0 :(得分:0)

如果你从db生成linq类,你可以这样做:

var JoinResult = from t1 in _context.table1
            join t2 in _context.table2 on t1.id equals t2.id
            select new 
            { 
               Id = t1.id
            };

_context - 是您的数据库。

默认 LinQ中的所有联接都是内部

如果您使用 LinqToSQL ,请不要使用.AsEnumerable()。这基本上会将整个表格从DB填充到你的记忆中。

答案 1 :(得分:0)

如果表格之间没有关系,则不需要任何加入。

你可以使用它。

            var Result = (from p in table1 .AsEnumerable()
                          from t in table2 .AsEnumerable()
                          where (t.id==1 || t.id==2)
                          select new
                          {
                              //whatever data you want.
                              ID = p.Field<int>("ID")                                     

                          }).ToList();

希望它会对你有所帮助。

答案 2 :(得分:0)

我认为你可以contains。请试试这个:

        selectList={1,2,3}//type of list (List<int>)

        var JoinResult = (from t1 in table1.AsEnumerable()
                      from t2 in table2.AsEnumerable
                      where (t2 => selectList.Contains(t2.id))
                      select new
                      {      
                          //what if you want take here
                          ID = p.Field<int>("ID")                                     

                      }).ToList();

答案 3 :(得分:0)

下面

select * from table1 Inner join table2 on table2.id in (1,2,3)
从技术上讲,table2.id in (1,2,3)只是一个过滤器(where),没有Inner Join,但Cross Join,即表之间没有连接(关系),但两者的笛卡尔积。

所以它确实是这样的

select * from table1, table2 where table2.id in (1,2,3)

因此将其翻译为LINQ可能就像这样

var t2Filter = new HasSet<int>(new int[] { 1, 2, 3});
var result = (
    from t1 in table1.AsEnumerable()
    from t2 in table2.AsEnumerable()
    where t2Filter.Contains(t2.Field<int>("id"))
    select new
    {
        ID = t1.Field<int>("ID")
        // ...
    }
).ToList();