繁体   English   中英

基于两个可互换列(LINQ)进行区分或分组

[英]Distinct or Group By Based on Two Interchangeable Columns (LINQ)

我有以下物品的清单

在此处输入图片说明

我想做的是纯粹基于团队名称使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM