我正在构建这个viewmodel,但是我不确定如何选择下面这个示例中的所有ListOfMeetingDates。我还需要将字符串格式化为完整的月份。任何帮助都很好。
List<Meeting> Meeting = new List<Meeting>();
List<MeetingDates> ListOfMeetingDates = new List<MeetingDates>();
ListOfMeetingDates.Add(new MeetingDates() { MeetingDatesId = 1, StartDate= "11-1-2020"});
ListOfMeetingDates.Add(new MeetingDates() { MeetingDatesId = 2, StartDate = "11-2-2020" });
Meeting.Add(new Meeting() { Meetingid = 1, MeetingName="a",ListOfMeetingDates= ListOfMeetingDates });
ListOfMeetingDates.Clear();
ListOfMeetingDates.Add(new MeetingDates() { MeetingDatesId = 3, StartDate = "11-5-2020" });
Meeting.Add(new Meeting() { Meetingid = 2, MeetingName = "b", ListOfMeetingDates = ListOfMeetingDates });
var listOfMeetings = Meeting
.Select(x => new MeetingViewModel
{
MeetingName = x.MeetingName,
MeetingDate = x.ListOfMeetingDates.SelectMany(z => z.StartDate)
}).ToList();
class Meeting
{
public int Meetingid { get; set; }
public string MeetingName { get; set; }
public List<MeetingDates> ListOfMeetingDates { get; set; }
}
class MeetingDates
{
public int MeetingDatesId { get; set; }
public string StartDate { get; set; }
}
class MeetingViewModel
{
public string MeetingName { get; set; }
public string MeetingDate { get; set; }
}
我正在寻找的输出
MeetingName = a
MeetingDate = November 1 2020 - November 2 2020
MeetingName = b
MeetingDate = November 5 2020
这样能行吗?
var listOfMeetings = Meeting
.Select(x => new MeetingViewModel
{
MeetingName = x.MeetingName,
MeetingDate = GetDateRangeFormatted(x.MeetingDates)
}).ToList();
private string GetDateRangeFormatted(IEnumerable<MeetingDates> meetingDates)
{
if (meetingDates.Count() == 0)
return String.empty;
if (meetingDates.Count() == 1)
return meetingDates.First().StartDate;
// this will only work if the dates are sorted correctly
return $"{meetingDates.First().StartDate} - {meetingDates.Last().StartDate}";
}
不过,我建议您稍微修改一下模型,这样您就可以更好地操作/设置日期格式:
class MeetingDates
{
public int MeetingDatesId { get; set; }
public DateTime StartDate { get; set; } // notice DateTime instead of string
}