如何分组日期和关联状态

时间:2014-11-27 15:49:58

标签: c# linq

所以我有以下数据:

State  Date
AK     11/27/2014   
AL     11/27/2014
HI     11/30/2014

我希望将数据显示在这样的网页上:

State    Date
AK, AL   11/27/2014
HI       11/30/2014

我正在使用Linq取回逗号分隔的状态列表和逗号分隔的日期列表。

但这些只是分配给2个单独的字符串

以下是我正在使用的内容:

State = Version.States
               .Aggregate(string.Empty, (c, state) =>
                   c + state.CountryState.State.StateShortName.ToString() + ", ")
                            .TrimEnd(',', ' '),
StartDate = Version.States
                   .Aggregate(string.Empty, (c, date) =>
                       c + date.StartDate.Date.ToShortDateString() + "," + System.Environment.NewLine)
                               .TrimEnd(',', ' ')

3 个答案:

答案 0 :(得分:1)

您可以尝试这样的事情:

var result = data.GroupBy(x=>x.Date)
                 .Select(x=>new {
                     Date = x.Key.ToShortDateString(),
                     Satet = String.Join(",",x.Select(y=>y.State))
            });

其中data包含您发布的表单中的所有数据。

答案 1 :(得分:1)

易: -

var result = states.GroupBy(x => x.Date)
                   .Select(x => new { State = String.Join(",",x.Select(z => z.State)), 
                                              Date = x.Key.ToShortDateString() });

工作Fiddle

答案 2 :(得分:0)

在预测合并状态之前,我倾向于在常见日期首先对数据进行分组。此外,String.Join通常比一般.Aggregate更容易折叠字符串。您没有发布完整的层次结构,但这是一个简化模型的解决方案:

public class StateVersion
{
    public string StateShortName;
    public DateTime Date;
}

var stateVersions = new List<StateVersion>
{
    new StateVersion { StateShortName = "AK", Date = new DateTime(2014, 11, 27)},
    new StateVersion { StateShortName = "AL", Date = new DateTime(2014, 11, 27)},
    new StateVersion { StateShortName = "HI", Date = new DateTime(2014, 11, 30)}
};

var aggStates = stateVersions.GroupBy(sv => sv.Date.ToShortDateString())
    .Select(g => String.Join(",", g.Select(x => x.StateShortName)) + " " + g.Key)
    .ToList();

foreach (var s in aggStates)
{
    Debug.WriteLine(s);
}

IdeOne Fiddle