使用LINQ为其每个属性连接2个对象

时间:2017-06-12 06:15:42

标签: c# linq

我创建了2个模型来存储sql查询的结果。现在我想加入他们每个星期...... (week1 = Record_id, week2 = Record_id) 获得一个新的Object,我将获得第一个模型中的所有数据,以及将“Category”模型中的数据映射到它。

我为它创建了一个新模型,但我不确定如何编写linq查询

第一个模型:

public class CustomData
{
    public string full_name { get; set; }
    public string location { get; set; }
    public int week1 { get; set; }
    public int week2 { get; set; }
    public int week3 { get; set; }
}

第二种模式:

public class Category
{
    public int Record_ID { get; set; }
    public int Color{ get; set; }
    public string Name { get; set; }
}

最终结果的新模型:

public class WeekView
{
    public string full_name { get; set; }
    public string location { get; set; }
    public Category week1 { get; set; }
    public Category week2 { get; set; }
    public Category week3 { get; set; }
}

2 个答案:

答案 0 :(得分:3)

这应该有效:

        List<CustomData> list = new List<CustomData>();
        list.Add(new CustomData() { full_name = "test", location = "test", week1 = 0, week2 = 1, week3 = 2 });
        list.Add(new CustomData() { full_name = "test2", location = "test2", week1 = 0, week2 = 12, week3 = 22 });
        List<Category> categories = new List<Category>();
        categories.Add(new Category { Color = 0, Name = "testName", Record_ID = 0 });
        categories.Add(new Category { Color = 1, Name = "testName1", Record_ID = 1 });
        categories.Add(new Category { Color = 2, Name = "testName2", Record_ID = 2 });
        categories.Add(new Category { Color = 3, Name = "testName3", Record_ID = 12 });
        categories.Add(new Category { Color = 4, Name = "testName4", Record_ID = 22 });
        List<WeekView> results = new List<WeekView>();
        results.AddRange(list.Select(x=> 
              new WeekView() { full_name = x.full_name, 
                               location = x.location, 
                               week1 = categories.FirstOrDefault(c => c.Record_ID == x.week1), 
                               week2 = categories.FirstOrDefault(c => c.Record_ID == x.week2), 
                               week3 = categories.FirstOrDefault(c => c.Record_ID == x.week3)
                              }));

答案 1 :(得分:0)

尝试以下内容:

var result = (from cd in CustomDatas
              join ca1 in Categories on cd.week1 equals ca.Record_ID into ca1r
              from ca1 in ca1r.DefaultIfEmpty()
              join ca2 in Categories on cd.week2 equals ca.Record_ID into ca2r
              from ca2 in ca2r.DefaultIfEmpty()
              join ca3 in Categories on cd.week3 equals ca.Record_ID into ca3r
              from ca3 in ca3r.DefaultIfEmpty()
              select new {
                    full_name = cd.full_name,
                    location = cd.location,
                    week1 = ca1,
                    week2 = ca2,
                    week3 = ca3
              }