簡體   English   中英

與自定義比較器不同

[英]Distinct with custom comparer

嘗試通過自定義比較器使用Distinct() ,但出現錯誤:

無法從用法中推斷出來。 嘗試顯式指定類型參數

Default比較器工作正常,但沒有給出我期望的結果。 我怎樣才能解決這個問題?

public class TimeEntryValidation
{
    public string EmployeeID { get; set; }
    public string EmployeeLocation { get; set; }
    public string EmployeeDepartment { get; set; }
    public int RowIndex { get; set; }
}

public class MyRowComparer : IEqualityComparer<TimeEntryValidation>
{
    public bool Equals(TimeEntryValidation x, TimeEntryValidation y)
    {
        return (x.EmployeeDepartment == y.EmployeeDepartment && x.EmployeeLocation == y.EmployeeLocation);
    }

    public int GetHashCode(TimeEntryValidation obj)
    {
        return obj.EmployeeID.GetHashCode(); 
    }
}

void Query(List<TimeEntryValidation> listToQuery)
{
    var groupedData =
        from oneValid in listToQuery
        group oneValid by oneValid.EmployeeID
            into g
        where g.Count() > 1
        select new {DoubleItems = g};
    var listItems = groupedData.Distinct(new MyRowComparer());
}

groupedData的類型是IEnumerable<{an anonymous type}>MyRowComparerIEqualityComparer<TimeEntryValidation>

目前尚不清楚您是否打算將listItems設為一組列表,還是想要實際的項目本身。

如果是后者,那么您可能想要這樣的東西:

void Query(List<TimeEntryValidation> listToQuery)
{
    var groupedData = from oneValid in listToQuery
                        group oneValid by oneValid.EmployeeID
                            into g
                            where g.Count() > 1
                            select  g ;
    var listItems = groupedData.SelectMany(group => group).Distinct(new MyRowComparer());
    //listItems is now an IEnumerable<TimeEntryValidation>
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM