c#如何找到重复的日期列表和组的描述

标签: Linq C#
发布时间: 2017/2/28 22:35:05
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

我有一个这样的对象︰

public DateLookupItem()
{
    Id = int.MinValue;
    Date = DateTime.MinValue;
    Description = string.Empty;
}

我有以上的对象的列表。现在我需要找到组按同一日期和串联那组的描述。

我需要输出这样的事情作为一个字符串,如果 2 日期列表中相同,另一种是不同︰

(Description/Description) Date, (Description) Date

我有工作,但很难读取跟踪以下代码。dateList is a DateLookupItem列表︰

string comma = string.Empty;

List<IGrouping<DateTime, DateLookupItem>> sameDates = dateList.GroupBy(x => x.Date).ToList();

foreach(IGrouping<DateTime, DateLookupItem> date in sameDates )
{
    string forwardSlash = string.Empty;
    displayDate += comma + "(";

    foreach(DateLookupItem d in date)
    {
        displayDate += forwardSlash + d.Description;
        forwardSlash = "/";
    }

    displayDate += ")" + " " + CELPDateTime.GetStringFromDateTime(date.Key);
    comma = ", ";
}

有没有办法将其转换到 linq 吗?或重构它,这样就容易看懂吗?

解决方法 1:

这应做到︰

var sameDates = from d in dateList
        group d.Description by d.Date.Date;

var displayDate = 
    String.Join(",", 
                sameDates
                .Select(date=>string.Format("({0}) {1}", 
                                   String.Join("/", date), 
                                    date.Key)
                       )
                );

你会需要更换 date.KeyCELPDateTime.GetStringFromDateTime(date.Key)

这里是我所用的代码的其余部分︰

void Main()
{
    var dateList = new List<DateLookupItem>();
    for(int i=0; i< 100; ++i) dateList.Add(new UserQuery.DateLookupItem());

    var sameDates = from d in dateList
            group d.Description by d.Date.Date;

    var displayDate = 
        String.Join(",", 
                    sameDates
                    .Select(date=>string.Format("({0}) {1}", String.Join("/", date), date.Key)));


    displayDate.Dump();
}


public class DateLookupItem
{
    static readonly Random rnd = new Random();
        public DateLookupItem()
        {
            Id = rnd.Next();
            Date = DateTime.Now.AddDays(rnd.Next(-5, 5) );
            Description = new string((char) rnd.Next(65, 91), rnd.Next(10)+1);
        }
    public int Id {get; set;}
    public DateTime Date {get; set;}
    public string Description {get; set;}
}
赞助商