将类列表拆分为具有相同值的类

时间:2017-11-12 22:09:22

标签: c#

我有课程结果:

class Result
{
    public Performance Result1{ get; set; }
    public Performance Result2{ get; set; }
    public Performance Result3{ get; set; }
    public Performance Result4{ get; set; }
    public string Lane { get; set; }

}

表演枚举:

public enum Performance
{
    trash,
    verylow,
    low,
    medium,
    good,
    high,
    veryhigh,
    Equals,
    Default,
    NoEnemy
}

我正在寻找一种更简洁的方法来拆分我的列表List<Result> FinalResults

到具有相同值的列表中,例如

var Ex1 = new Result {Result1 = Performance.trash, Result2 = Performance.trash, Result3 = Performance.trash};
var Ex2 = new Result {Result1 = Performance.Low, Result2 = Performance.VeryLow, Result3 = Performance.good};
var Ex3 = new Result {Result1 = Performance.high, Result2 = Performance.trash, Result3 = Performance.trash};
var Ex4 = new Result {Result1 = Performance.trash, Result2 = Performance.VeryLow, Result3 = Performance.good};

Ex1 Ex4 具有相同的 result1 ,因此我将它们放在同一个列表中,因此 Ex2 Ex4 他们有相同的 result2 等。

编辑:

使用以下示例我将列出这些列表:

List<Result> List1 = {Ex1, Ex2};
List<Result> List1 = {Ex4, Ex4};

这些示例中有更多相等的值,但我想在列表中添加一个值等于

编辑2:

我尝试使用GroupBy

var low = Current.GamesResults.GroupBy(x => x.result1 == Performance.trash || x.result1 == Performance.verylow
  || x.result1 == Performance.low);
var Normal = Current.GamesResults.GroupBy(x => x.result1 == Performance.good || x.result1 == Performance.Equals
  || x.result1 == Performance.medium);
var High = Current.GamesResults.GroupBy(x => x.result1 == Performance.high || x.result1 == Performance.veryhigh);

但问题是我必须做很多次,这取决于我在结果类

中有多少属性(Result1,rResult2 ...)

提前致谢

1 个答案:

答案 0 :(得分:0)

由于枚举中的前3项是0,1,2,而后3项是3,4,5,因此可以按属性除以3(未测试)对结果进行分组:

var lookup = Current.GamesResults.ToLookup(r => r.Result1 / 3);
var Low = lookup[0], Normal = lookup[1], High = lookup[2];

使用所有属性会有点复杂,因为您需要根据最常用的属性创建一个确定组的方法:

int mostFrequent(Result r) => new [] { r.Result1, r.Result2, r.Result3, r.Result4 }
    .GroupBy(p => p).Max(g => Tuple.Create(g.Count(), g.Key)).Item2 / 3;

var lookup = Current.GamesResults.ToLookup(mostFrequent);
var Low = lookup[0], Normal = lookup[1], High = lookup[2];
相关问题