【问题标题】:Union on datatable数据表上的联合
【发布时间】:2013-02-05 13:02:09
【问题描述】:

我将如何在 Linq 中转换此 SQL 查询,抱歉,我不是 LINQ 方面的专家

select ConnectionId
from LearnerConnections
where LearnerId = 1
union
select LearnerId
from LearnerConnections
where ConnectionId = 1

我也可以编写 DataTable 方法来获取结果(如 DataTable.Select() 方法)吗?

提前致谢

【问题讨论】:

    标签: c# asp.net


    【解决方案1】:

    类似的东西

    LearnerConnections.Where(x => x.LearnerId == 1)
                      .Select(m => m.ConnectionId)
                      .Union(LearnerConnections.Where(l => l.ConnectionId ==1)
                                               .Select(lc => lc.LearnerId)
    
                      );
    

    有一个数据表,它应该看起来像

      dtLearnerConnections.AsEnumerable()
                          .Where(m => m.Field<int>("LearnerId") == 1)
                          .Select(m => m.Field<int>("ConnectionId"))
                          .Union(dtLearnerConnections.AsEnumerable()
                                                     .Where(x => x.Field<int>("ConnectionId") == 1)
                                                     .Select(x => x.Field<int>("LearnerId"))
                          );
    

    【讨论】:

      【解决方案2】:

      希望对你有帮助

      var results = (from l in LearnerConnections where l.LearnerId == 1 
                       select l.ConnectionId).Union(from a in LearnerConnections 
                       where a.ConnectionId == 1 select l.LeaenerId);
      

      【讨论】:

        【解决方案3】:
        var result = (from lc in LearnerConnections
                      where lc.LearnerId == 1
                      select lc.ConnectionId)
                      .Union
                     (from lc in LearnerConnections
                      where lc.ConnectionId == 1
                      select lc.LearnerId);
        

        如果您使用的是 DataTables,这涉及到使用 LINQ to DataSet。这个 SO question 也可能对您有所帮助。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-05-27
          相关资源
          最近更新 更多