计数、排序描述和 select ASP.NET 的前 4 个值
Count, order desc and select top 4 values for ASP.NET
我正在尝试创建一个 table 来显示我的 .NET 应用程序数据库中排名前 4 位的国籍。我可以在 this.
之后使用 SQL 来完成
这是 sql
中的结果
但是,我的申请需要的是
我试过在视图中使用 LINQ 和 var,但无法获取。我看到 并尝试跟随但不太明白
员工模型
public class employees
{
public int eeID { get; set; }
public string Name { get; set; }
public string Gender { get; set; }
public string Nationality { get; set; }
}
您可以执行以下操作
- 存储按人数排序的分组国籍
- 获得最佳结果,使用
Enumerable.Take
- 获取不应包括最高记录的其他民族的数量,为此,您可以使用
Enumerable.Skip
- 第 2 点和第 3 点的 Concat 结果。
- 将最终输出传递给视图。
示例代码。请参考此link以获取工作代码
// Your Logic
var topRecordsCount = 4;
var groupedResult = list
.GroupBy(x => x.Nationality)
.OrderByDescending(x => x.Count());
var topRecords = groupedResult
.Take(topRecordsCount)
.Select(x => new FinalResult {Nationality = x.Key, Total = x.Count()}).ToList();
var othersCount = groupedResult.Skip(topRecordsCount).Select(x => x.Count()).Sum();
var othersRecord = new FinalResult { Nationality = "Others", Total = othersCount};
topRecords.Add(othersRecord);
foreach(var top in topRecords)
Console.WriteLine(top.Nationality + " - " + top.Total);
// model to store the final output
public class FinalResult {
public string Nationality { get; set; }
public int Total { get; set; }
}
我正在尝试创建一个 table 来显示我的 .NET 应用程序数据库中排名前 4 位的国籍。我可以在 this.
之后使用 SQL 来完成这是 sql
中的结果但是,我的申请需要的是
我试过在视图中使用 LINQ 和 var,但无法获取。我看到
员工模型
public class employees
{
public int eeID { get; set; }
public string Name { get; set; }
public string Gender { get; set; }
public string Nationality { get; set; }
}
您可以执行以下操作
- 存储按人数排序的分组国籍
- 获得最佳结果,使用
Enumerable.Take
- 获取不应包括最高记录的其他民族的数量,为此,您可以使用
Enumerable.Skip
- 第 2 点和第 3 点的 Concat 结果。
- 将最终输出传递给视图。
示例代码。请参考此link以获取工作代码
// Your Logic
var topRecordsCount = 4;
var groupedResult = list
.GroupBy(x => x.Nationality)
.OrderByDescending(x => x.Count());
var topRecords = groupedResult
.Take(topRecordsCount)
.Select(x => new FinalResult {Nationality = x.Key, Total = x.Count()}).ToList();
var othersCount = groupedResult.Skip(topRecordsCount).Select(x => x.Count()).Sum();
var othersRecord = new FinalResult { Nationality = "Others", Total = othersCount};
topRecords.Add(othersRecord);
foreach(var top in topRecords)
Console.WriteLine(top.Nationality + " - " + top.Total);
// model to store the final output
public class FinalResult {
public string Nationality { get; set; }
public int Total { get; set; }
}