简体   繁体   中英

LINQ to SQL Join orderby

i am new to LINQ and joins, so Please forgive me if I am asking it wrong. I have two tables

Table1

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

Table2

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.

Can you guys help me, I really need to figure out how Joins works with 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

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.

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:

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 . 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 .

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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