基于两个可互换列(LINQ)的区别或分组

时间:2017-01-01 23:32:26

标签: c# linq distinct

我有一个包含以下项目的列表

enter image description here

我想做的是使用纯粹基于团队名称的linq执行某种分组或不同的分组。对于提供的示例,即使名称存储在记录中的不同变量中,也只会返回一个记录,因为它们是相同的团队互相播放。

返回哪条记录并不重要。

提前感谢您的帮助!

2 个答案:

答案 0 :(得分:3)

我能想到的一种方法是按“标准化”复合键进行分组,其中标准化意味着例如第一个键是两个中较小的一个,第二个键是较大的:

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();

答案 1 :(得分:1)

您可以使用自定义比较器:

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; }
}