你有3个模型列表,它们包含奇数个元素,它们都是由userId加入的。
现实世界中的这3个模型列表将在执行时从3个存储过程中获取数据。 我正在尝试使用Linq来对外加入他们,"我不知道怎么做"。我知道在Linq中有一个左连接但是说如果出现第一个列表被填充的情况,然后在第二个和/或第三个列表被填充之前,新用户被添加了所有3个表的相关数据。 因此,新用户数据将位于第二个和第三个表上,而不是第一个表 我希望在将它们与Linq一起收集之后,我的ViewModel会显示所有数据吗? 这是当您需要右连接时,因为您希望在左表数据上显示空值。
有人知道是否有办法为此进行正确的加入,还是有更好的方法? 下面是3对象列表,我需要将它们用于使用Linq为我的Viewmodel收集。
请提出建议。
B
class Program
{
static void Main(string[] args)
{
List<CommissionBrokerReport> dailyReports = new List<CommissionBrokerReport>(new CommissionBrokerReport[]
{
new CommissionBrokerReport { userId = 101, firstName = "Bruce", lastName = "Wayne", value = 17433.3333M, average = 0M },
new CommissionBrokerReport { userId = 303, firstName = "Selina", lastName = "Kyle", value = 7279.13M, average = 0M }
});
List<CommissionBrokerReport> weeklyReports = new List<CommissionBrokerReport>(new CommissionBrokerReport[]
{
new CommissionBrokerReport { userId = 101, value = 0M, average = 7532.9167M },
new CommissionBrokerReport { userId =303, value = 0M, average = 0M },
new CommissionBrokerReport { userId = 404, value = 33.3333M, average = 666.6666M }
});
List<CommissionBrokerReport> monthlyReports = new List<CommissionBrokerReport>(new CommissionBrokerReport[]
{
new CommissionBrokerReport { userId = 101, value = 37550.0000M, average = 4653.7500M },
new CommissionBrokerReport { userId = 303, value = 0M, average = 0M },
new CommissionBrokerReport { userId = 404, value = 33.3333M, average = 666.6666M },
new CommissionBrokerReport { userId = 505, value = 55.5555M, average = 10000.0000M }
});
}
}
答案 0 :(得分:1)
这是join
3 list
的一种方式,可以获取null
来自不同list
的丢失记录的结果。
var MonthlyWeeklyRpt =
from m in monthlyReports
join w in weeklyReports on m.userId equals w.userId into weeklyrpt
from w in weeklyrpt.DefaultIfEmpty()
select new
{
MonthlyReports = m,
WeeklyReports = w
};
var MonthlyWeeklyDailyRpt =
from q in MonthlyWeeklyRpt
join d in dailyReports on q.MonthlyReports.userId equals d.userId into dailyrpt
from d in dailyrpt.DefaultIfEmpty()
select new
{
MonthlyReports = q.MonthlyReports,
WeeklyReports = q.WeeklyReports,
DailyReports =d
};
foreach (var item in MonthlyWeeklyDailyRpt)
{
Console.WriteLine("monthly reports");
Console.WriteLine(item.MonthlyReports.userId + " " + item.MonthlyReports.value);
if (item.WeeklyReports != null)
{
Console.WriteLine("weekly reports");
Console.WriteLine(item.WeeklyReports.userId + " " + item.WeeklyReports.value);
}
else
Console.WriteLine("null weekly report");
if (item.DailyReports != null)
{
Console.WriteLine("daily reports");
Console.WriteLine(item.DailyReports.userId + " " + item.DailyReports.value);
}
else
Console.WriteLine("null daily report");
Console.WriteLine(" ");
}
它将打印以下输出
monthly reports
101 37550.0000
weekly reports
101 0
daily reports
101 17433.3333
monthly reports
303 0
weekly reports
303 0
daily reports
303 7279.13
monthly reports
404 33.3333
weekly reports
404 33.3333
null daily report
monthly reports
505 55.5555
null weekly report
null daily report
我希望它会帮助你。