LINQ OrderBy and StringBuilder



我有以下自定义类

public class Album
{
public string PhotoName { get; set; }
public string Location { get; set; }
public DateTime DateTime { get; set; }
}

我有一个这种类型的列表,我按位置排序,然后按日期时间排序

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));

只是想知道我怎样才能达到我所需的要求?

更新:这是我的完整代码,其中包含我应该放置字符串生成器的部分:

public static string Solution(string S)
{
string[] group = S.Split("rn");
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"

并且生成的字符串生成器必须是

Warsaw01
London01
Warsaw02
Paris01
Paris02
London02

您可以使用GroupBySelect函数的组合,其中还包括索引。而不是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);

可以使用GroupByAggregate扩展方法的组合

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();

最新更新