[英]Distinct or Group By Based on Two Interchangeable Columns (LINQ)
我能想到的一种方法是按“归一化”组合键分组,其中归一化意味着例如第一个键是两个中的较小者,而第二个则是较大的:
var result = input
.GroupBy(x => new
{
K1 = string.Compare(x.Team1, x.Team2) < 0 ? x.Team1 : x.Team2,
K2 = string.Compare(x.Team1, x.Team2) < 0 ? x.Team2 : x.Team1,
})
.Select(g => g.First())
.ToList();
您可以使用自定义比较器:
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
var fixtures = new List<Match> {
new Match { Team1 = "Eagles", Team1Score = 2, Team2 = "Hawks", Team2Score = 4},
new Match { Team1 = "Hawks", Team1Score = 1, Team2 = "Eagles", Team2Score = 2 },
};
var results = fixtures
.GroupBy(x => x, new MatchComparer())
.Select(x => new { x.Key.Team1, x.Key.Team2, Team1Total = x.Sum(s => s.Team1Score), Team2Total = x.Sum(s => s.Team2Score) });
}
}
public class MatchComparer : IEqualityComparer<Match>
{
public bool Equals(Match x, Match y)
{
return (x.Team1 == y.Team1 && x.Team2 == y.Team2) ||
(x.Team1 == y.Team2 && x.Team2 == y.Team1);
}
public int GetHashCode(Match obj)
{
return obj.Team1.GetHashCode() + obj.Team2.GetHashCode();
}
}
public class Match
{
public string Team1 { get; set;}
public int Team1Score { get; set; }
public string Team2 { get; set; }
public int Team2Score { get; set; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.