我有以下自定义课程
public class Album
{
public string PhotoName { get; set; }
public string Location { get; set; }
public DateTime DateTime { get; set; }
}
,我有一个该类型的列表,该列表按位置,然后按DateTime排序
List<Album> SortedList = list
.OrderBy(o => o.Location)
.ThenBy(o => o.DateTime)
.ToList();
现在我需要有一个StringBuilder,它将在位置旁边附加索引号,但是索引号应取决于位置,而不取决于列表
例如,我的列表包含:
> a | London | 12:00:00 AM
> b | London | 1:00:00 AM
> c | Warsaw | 1:30:00 AM
> d | Warsaw | 1:45:00 AM
我的StringBuilder必须是:
> London01
> London02
> Warsaw01
> Warsaw02
我尝试使用它,但是它返回列表的索引号
var query = SortedList.IndexOf(list.SingleOrDefault(i => i.DateTime == a.DateTime));
只想知道如何满足我的要求?
更新:这是我完整的代码,其中应放置stringbuilder的部分:
public static string Solution(string S)
{
string[] group = S.Split("\r\n");
List<Album> list = new List<Album>();
StringBuilder sb = new StringBuilder();
foreach (string g in group)
{
string[] album = g.Split(',');
Album a = new Album();
a.PhotoName = album[0];
a.Location = album[1];
a.DateTime = DateTime.Parse(album[2]);
list.Add(a);
}
List<Album> SortedList = list.OrderBy(o => o.Location).ThenBy(o => o.DateTime).ToList();
foreach (string g in group)
{
string[] album = g.Split(',');
Album a = new Album();
a.PhotoName = album[0];
string[] photodetails = a.PhotoName.Split('.');
a.Location = album[1];
a.DateTime = DateTime.Parse(album[2]);
//this is the part where I must figure out how to build the string
// var query = SortedList.IndexOf(list.SingleOrDefault(i => i.DateTime == a.DateTime));
sb.AppendLine(a.Location + query + "." + photodetails[1]);
}
string res = sb.ToString();
return res;
}
字符串S的格式如下:
@"photo.jpg, Warsaw, 2013-09-05 14:08:15
john.png, London, 2015-06-20 15:13:22
myFriends.png, Warsaw, 2013-09-05 14:07:13
Eiffel.jpg, Paris, 2015-07-23 08:03:02
pisatower.jpg, Paris, 2015-07-22 23:59:59
BOB.jpg, London, 2015-08-05 00:02:03"
,生成的StringBuilder必须是
Warsaw01
London01
Warsaw02
Paris01
Paris02
London02
答案 0 :(得分:1)
您可以结合使用GroupBy
和Select
函数,该函数还包含索引。比SelectMany
更加平坦。
var result = list
.OrderBy(o => o.Location)
.ThenBy(o => o.DateTime)
.GroupBy(o => o.Location)
.SelectMany(o => o.Select((x,i) => x.Location + (i + 1).ToString("d2")));
如果您希望将其转换为字符串,则不需要StringBuilder,只需执行以下操作:
var resultString = string.Join("\n", result);
答案 1 :(得分:0)
您可以结合使用GroupBy
和Aggregate
扩展方法
var output =
albums.GroupBy(album => album.Location)
.OrderBy(group => group.Key)
.SelectMany(group => group.OrderBy(album => album.DateTime)
.Select((album, i) => $"{album.PhotoName}{(i+1):00}"))
.Aggregate(new StringBuilder(),
(builder, item) => builder.AppendLine(item))
.ToString();