如何在LINQ中将一个表与两个引用表链接?

时间:2012-01-22 10:02:51

标签: c# linq

我有以下内容:

   IEnumerable<Job> jobs

   jobs = from t in table.GetAll()
             select new Job
            {
                Key1 = t.Key1,
                Key2 = t.Key2,
                Title = t.Title,
                Status = t.Status,
                Type = t.Type
            };

“状态”和“类型”字段是键,这些键的值存储在以下内容中:

refStatus = from t in ref.GetAll()
           select new Ref
           {
                Key1 = "Status"
                Key2 = t.Key2,    // key that links to Status in the Jobs
                Title = t.Title   // Text value of the key
           }

  refType = from t in ref.GetAll()
           select new Ref
           {
                Key1 = "Type"
                Key2 = t.Key2,    // key that links to Type in the Jobs
                Title = t.Title   // Text value of the key
           }

LINQ中是否有一种方法可以将refStatus和refType表链接到第一个表,然后让我的作业报告显示Status和Type的文本值而不仅仅是键?

public abstract class Job
{
    public string Key1 { get; set; }
    public string Key2 { get; set; }
    public string Title { get; set; }
    public string Status { get; set; }
    public string Type { get; set; }
}

public abstract class Ref
{
    public string Key1 { get; set; }
    public string Key2 { get; set; }
    public string Title { get; set; }
}

1 个答案:

答案 0 :(得分:3)

尝试以下方法:

var results =
    from j in table.GetAll()
    join s in refTableStatuses.GetAll() on j.Status equals s.Key2
    join t in refTableTypes.GetAll() on j.Type equals t.Key2
    select new Job
    {
        Key1 = j.Key1,
        Key2 = j.Key2,
        Title = j.Title,
        Status = s.Title, // value from Ref (Status) s
        Type = t.Title    // value from Ref (Type) t
    };

您可能需要以某种方式区分状态和类型(因为它们来自同一个表并由同一实体表示)。由于您没有解释如何区分它们,我更新了我的查询变量以反映它。