public async Task<IActionResult> GetMemberAndBookingLineChartData()
{
var bookingData = _unitOfWork.Booking.GetAll(u => u.BookingDate >= DateTime.Now.AddDays(-30) && u.BookingDate.Date <= DateTime.Now).GroupBy(b => b.BookingDate.Date).Select(u => new
{
DateTime = u.Key,
NewBookingCount = u.Count(),
});
var customerData = _unitOfWork.User.GetAll(u => u.CreatedDAt >= DateTime.Now.AddDays(-30) && u.CreatedDAt.Date <= DateTime.Now).GroupBy(b => b.CreatedDAt.Date).Select(u => new
{
DateTime = u.Key,
NewCustomerCount = u.Count(),
});
var leftJoin = bookingData.GroupJoin(customerData, booking => booking.DateTime, customer => customer.DateTime, (booking, customer) => new
{
booking.DateTime,
booking.NewBookingCount,
NewCustomerCount = customer.Select(x => x.NewCustomerCount).FirstOrDefault()
});
var rightJoin = customerData.GroupJoin(bookingData, customer => customer.DateTime, booking => booking.DateTime, (customer, booking) => new
{
customer.DateTime,
customer.NewCustomerCount,
NewBookingCount = booking.Select(x => x.NewBookingCount).FirstOrDefault(),
});
//var mergedData = leftJoin.Union((rightJoin).OrderBy(x => x.DataTime).ToList());
var mergedData = rightJoin.Union(leftJoin.OrderBy(x => x.DateTime)).ToList();
var newBookingData = mergedData.Select(x => x.NewBookingCount).ToArray();
var newCustomerData = mergedData.Select(x => x.NewCustomerCount).ToArray();
var categories = mergedData.Select(x => x.DataTime.ToString("MM/dd/yyyy")).ToArray();
List<CharData> charDataList = new()
{
new CharData
{
Name="New Bookings",
Data=newBookingData
},
new CharData
{
Name="New Members",
Data=newCustomerData
}
};
LineChartVM lineChartVM = new()
{
Categories = categories,
Series = charDataList
};
return Json(lineChartVM);
}
错误是
var mergedData = rightJoin.Union(leftJoin.OrderBy(x => x.DateTime)).ToList();
不起作用。
请给我一个解决方案
LINQ Union() 方法组合两个序列并删除重复项,但您似乎想保留所有元素然后对它们进行排序。
// Merge data using Concat instead of Union to retain all elements
var mergedData = rightJoin.Concat(leftJoin).OrderBy(x => x.DateTime).ToList();
通过使用 Concat 而不是 Union,您可以保留两个序列中的所有元素,然后您可以根据需要使用 OrderBy 对它们进行排序