简体   繁体   English

LINQ to SQL连接顺序

[英]LINQ to SQL Join orderby

i am new to LINQ and joins, so Please forgive me if I am asking it wrong. 我是LINQ的新手并加入,所以如果我问错了,请原谅我。 I have two tables 我有两张桌子

Table1 表格1

id   name    date
1    Mike    20-10-15
2    John    21-10-15
3    Sam     23-10-15

Table2 表2

id   name   date
1    Ashle  19-10-15
2    Lily   21-10-15
3    Jeni   22-10-15
4    April  23-10-15

I need 5 records using Joins and should be orderby Date, most recent records. 我需要使用Joins的5条记录,并且应该是orderby Date(最新记录)。

Can you guys help me, I really need to figure out how Joins works with orderby. 你们能帮我吗,我真的需要弄清楚Joins如何与orderby一起工作。 Thanks 谢谢

EDIT: They are two different tables so no foreign key, so I think I can't use Join, so so far what I have done is like this 编辑:他们是两个不同的表,所以没有外键,所以我想我不能使用Join,到目前为止我所做的就是这样

var combinddata = (from t1 in db.Table1
                        select t1.id)
                            .Concat(from t2 in db.Table2
                                    select t2.id);

I don't know how to get only 5 records how to compare records from both tables on DateTime base. 我不知道如何只获取5条记录,如何在DateTime基础上比较两个表中的记录。

Output should be 输出应为

  1. Sam 山姆
  2. April 四月
  3. Jeni 杰尼
  4. John 约翰
  5. Lily 百合

You can concatenate equal anonymous types from different tables. 您可以连接来自不同表的相等匿名类型。 If you also select the dates, you can sort by them, in descending order, and take the first 5 records: 如果您还选择日期,则可以按降序对日期进行排序,并获取前5条记录:

Table1.Select (t1 => 
    new
    {
        Id = t1.Id,
        Name = t1.Name,
        Date = t1.Date
    }
).Concat(
Table2.Select (t2 => 
    new
    {
        Id = t2.Id,
        Name = t2.Name,
        Date = t2.Date
    }
))
.OrderByDescending (x => x.Date).Take(5)

Note that this gives precedence to items in Table1 . 请注意,这优先于Table1项目。 If item 5 and 6 in the concatenated result are on the same date, but from Table1 and Table2 , respectively, you only get the item from Table1 . 如果合并结果中的项目5和6处于同一日期,但分别来自Table1Table2 ,则只能从Table1获得该项目。

If you want, you can select only the names from this result, but I assume that your output only shows the intended order of record, not the exact expected result. 如果需要,您可以从此结果中仅选择名称,但我假设您的输出仅显示记录的预期顺序,而不显示确切的预期结果。

Try this way 试试这个

var combinddata = (from t1 in db.Table1
                        select t1.Name)
                            .Concat(from t2 in  db.Table2 
                                    select t2.Name).OrderByDescending(x => x.date).Take(5);
var query = 
    from Table1 in table1
    join Table2 in table2 on table1.id equals table2.id 
    orderby table1.date ascending 
    select table1.date;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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