gpt4 book ai didi

c# - 根据列表中的值设置排名

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:05:32 24 4
gpt4 key购买 nike

我正在努力寻找更好的方法来解决我的问题。我有一个属性列表。有些属性应该“排名”(谁更好)。

数据结构如下:

public class MovieRankData
{
public Guid MovieId { get; set; }
public RankData TotalViews { get; set; }
public RankData TotalMoney { get; set; }
}

public class RankData
{
public string Name { get; set; }
public double? Value { get; set; }
public int Rank { get; set; }
}

而且非常简单的代码(请看评论):

var movieRankData = new List<MovieRankData>
{
new MovieRankData
{
MovieId = Guid.NewGuid(),
TotalViews = new RankData {Name = "Total Movie View", Value = 985 }, // Rank should be 2 (of 3)
TotalMoney = new RankData {Name = "Total Movie Money", Value = 525.12}, // Rank should be 1 (of 3)
},

new MovieRankData
{
MovieId = Guid.NewGuid(),
TotalViews = new RankData {Name = "Total Movie View", Value = 812}, // Rank should be 3 (of 3)
TotalMoney = new RankData {Name = "Total Movie Money", Value = 100}, // Rank should be 3 (of 3)
},

new MovieRankData
{
MovieId = Guid.Empty,
TotalViews = new RankData {Name = "Total Movie View", Value = 1000}, // Rank should be 1 (of 3)
TotalMoney = new RankData {Name = "Total Movie Money", Value = 321}, // Rank should be 2 (of 3)
}
};

我想到了丑陋的 foreach,许多临时变量来比较和设置 Rank 属性。

遍历每个元素、将其与其他元素进行比较并对其进行评分的更好方法是什么?

多谢指教!

最佳答案

下面是我的做法:

var byTotalViews = movieRankData.OrderByDescending(m => m.TotalViews.Value).ToList();
var byTotalMoney = movieRankData.OrderByDescending(m => m.TotalMoney.Value).ToList();

foreach (var movie in movieRankData)
{
movie.TotalViews.Rank = byTotalViews.IndexOf(movie) + 1;
movie.TotalMoney.Rank = byTotalMoney.IndexOf(movie) + 1;
}

尽管这不会处理 TotalViewsTotalMoneynull 值。如果您告诉我在这种情况下该怎么做,我会修改我的答案。由于可空比较的工作方式,我当前的解决方案将最高等级分配给 null

一个合理的解决方案是使 Rank 也可以为 null,如果 Valuenull,则将其设置为 null .

编辑:另请阅读@GiladGreen 在评论中提出的性能改进建议。

编辑 2: 这是基于词典的版本,在大型集合上表现良好。首先我们定义一个函数来计算排名并将它们存储在字典中:

private static Dictionary<MovieRankData, int> CalculateRanks(
List<MovieRankData> movieRankData,
Func<MovieRankData, double?> orderKeySelector)
{
return movieRankData
.OrderByDescending(orderKeySelector)
.Select((item, index) => new { item, index })
.ToDictionary(e => e.item, e => e.index + 1);
}

然后我们使用该函数生成byTotalViewsbyTotalMoney 字典:

var byTotalViews = CalculateRanks(movieRankData, m => m.TotalViews.Value);
var byTotalMoney = CalculateRanks(movieRankData, m => m.TotalMoney.Value);

foreach (var movie in movieRankData)
{
movie.TotalViews.Rank = byTotalViews[movie];
movie.TotalMoney.Rank = byTotalMoney[movie];
}

关于c# - 根据列表中的值设置排名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41879223/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com