如何使用linq从另一个表中订购具有匹配ID的数据?

时间:2014-03-26 14:26:06

标签: c# sql linq

所以我有2个表,我试图从表1中检索数据,但是我需要它排序。表1包含表2中的ID,它引用了一个字符串,我需要在表2中通过该字符串对表1数据进行排序。

例如......

表1

   COL_A    |    COL_B   |   COL_C
     1      |      3     |   sample
     2      |      1     |    test
     3      |      2     |   string

表2

   COL_A    |    COL_B
     1      |    my name
     2      |    his name
     3      |    her name

所以我需要通过COL_B对表1中的所有数据进行排序,但是按表2中的字符串对其进行排序,其中ID与表1 COL_B和表2 COL_A匹配。

如何使用LINQ执行此操作?

4 个答案:

答案 0 :(得分:2)

您基本上需要连接两个表,然后按TABLE2.COL_B排序,然后选择TABLE1。 linq表达式下面应该有效。

from t1 in TABLE1
join t2 in TABLE2 on t1.COL_B equals t2.COL_A
orderby t2.COL_B
select t1

答案 1 :(得分:1)

我已经给出了以下解决方案

class Table1
{
    public int IdA { get; set; }
    public int IdB { get; set; }
    public string Table1StrValue { get; set; }
}

class Table2
{
    public int IdA { get; set; }
    public string Table2StrValue { get; set; }
}

var table1List = new List<Table1>()
    {
        new Table1 {IdA = 1, IdB = 3, Table1StrValue = "sample"},
        new Table1 {IdA = 2, IdB = 1, Table1StrValue = "test"},
        new Table1 {IdA = 3, IdB = 2, Table1StrValue = "string"},
    };
var table2List = new List<Table2>()
    {
        new Table2 {IdA = 1, Table2StrValue = "my Name"},
        new Table2 {IdA = 2, Table2StrValue = "his Name"},
        new Table2 {IdA = 3, Table2StrValue = "her Name"},
    };

var result = from table2 in table2List
        join table1 in table1List on table2.IdA equals table1.IdA
        orderby table2.Table2StrValue
        select new {table2.IdA, table2.Table2StrValue, table1.Table1StrValue};

答案 2 :(得分:1)

所以我写了这篇文章,并用Musa来帮助完成它。我认为这就是你想要的

public class table1
{
   public int a;
   public int b;
   public string c;
}

public class table2
{
   public int a;
   public string b;
}

void Main()
{
List<table1> table1 = new List<table1>()
{
    new table1(){ a=1,b=2, c="RAWR"},
    new table1(){ a=2,b=4, c="DERP"},
    new table1(){ a=3,b=1, c="FOO"},
    new table1(){ a=4,b=3, c="BAR"},
};

List<table2> table2 = new List<table2>()
{
    new table2(){a=1,b="A"},
    new table2(){a=2,b="B"},
    new table2(){a=3,b="D"},
    new table2(){a=4,b="C"},
};

var something = from t1 in table1
join t2 in table2 on t1.b equals t2.a
orderby t2.b
select t1;

Console.WriteLine (something);

}

答案 3 :(得分:0)

这可能是最短的方式。

var ret = TABLE1.Join(TABLE2, a => a.COL_A, b => b.COL_A, (a, b) => new {COL_C = b.COL_C)}).OrderBy(s => s.COL_C);