我想以最有效的方式对“条目”列上给定列表中的条目进行排序。下面是我的i条目外观的示例。
#No Detail Entry Number Rate
1 Carpool at 5$ C 1 5
Carpool at 5$ H 2 5
2 Played Cricket at 2$ X 1 2
Played Cricket at 2$ O 2 2
3 Done something at 4$ "" 0 4
4 Done something else at 9$ M 1 9
5 Watched movie at 6$ B 1 6
Watched movie at 6$ Z 2 6
有关数据的一些解释:
我想按照上述规则通过升序或降序对Entry列进行排序。
我的解决方案:
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApplication1
{
internal class Data
{
public string Detail { get; set; }
public string Entry { get; set; }
public int Number { get; set; }
public int Rate { get; set; }
}
internal class Program
{
private static void Main(string[] args)
{
List<Data> entries = new List<Data>();
// Clubbed entry...While sorting only consider entry with Number set to 1. They will have same rate and Detail.
entries.Add(new Data() { Detail = "Carpool at 5$", Entry = "C", Number = 1, Rate = 5 });
entries.Add(new Data() { Detail = "Carpool at 5$", Entry = "H", Number = 2, Rate = 5 });
// Clubbed entry
entries.Add(new Data() { Detail = "Played Cricket at 2$", Entry = "X", Number = 1, Rate = 2 });
entries.Add(new Data() { Detail = "Played Cricket at 2$", Entry = "O", Number = 2, Rate = 2 });
// entry which have empty Entry value such entries will have Number set to 0
entries.Add(new Data() { Detail = "Done something at 4$", Entry = "", Number = 0, Rate = 4 });
// entry which will not have an pair and Number column for such entries would be set to 1 and
// there wouldn't be any entry in list which have same detail and rate with Number coloumn set to 2
entries.Add(new Data() { Detail = "Done something else at 9$", Entry = "M", Number = 1, Rate = 9 });
// Clubbed entry
entries.Add(new Data() { Detail = "Watched movie at 6$", Entry = "B", Number = 1, Rate = 6 });
entries.Add(new Data() { Detail = "Watched movie at 6$", Entry = "Z", Number = 2, Rate = 6 });
// Sorting on Entry Coloumn
var sortedList = entries.GroupBy(x => x.Detail).OrderBy(x => x.FirstOrDefault(y => y.Number <= 1).Entry).SelectMany(x => x).ToList();
}
}
}
输出:
Detail Entry Number Rate
Done something at 4$ "" 0 4
Watched movie at 6$ B 1 6
Watched movie at 6$ Z 2 6
Carpool at 5$ C 1 5
Carpool at 5$ H 2 5
Done something else at 9$ M 1 9
Played Cricket at 2$ X 1 2
Played Cricket at 2$ O 2 2
问题:
答案 0 :(得分:1)
您可以通过创建匿名对象来按“费率”和“详细信息”分组。如果您使用的是size_t i = 0;
s = malloc(1);
/* TODO: check for s != NULL */
while ((c = getchar()) != '\n') {
s[i] = c;
i++;
s = realloc(s, i + 1);
/* TODO: check for s != NULL */
}
s[i] = '\0';
,则应该处理FirstOrDefault
返回null
的可能性。如果您不应该拥有不包含0或1的?.
的组,则应该只使用Number
。您应该根据First
对组中的成员进行排序:
Number