如何对日期和关联的状态进行分组
本文关键字:状态 关联 日期 | 更新日期: 2023-09-27 18:32:25
所以我有以下数据:
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(',', ' ')
简单:-
var result = states.GroupBy(x => x.Date)
.Select(x => new { State = String.Join(",",x.Select(z => z.State)),
Date = x.Key.ToShortDateString() });
工作小提琴。
你可以尝试这样的事情:
var result = data.GroupBy(x=>x.Date)
.Select(x=>new {
Date = x.Key.ToShortDateString(),
Satet = String.Join(",",x.Select(y=>y.State))
});
其中data
以您发布的表单保存您的所有数据。
我倾向于先在共同日期对数据进行分组,然后再投影出组合状态。此外,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