开发者

Create New Distinct List(of T) from Existing List(of T) Using LINQ

How can I get a new di开发者_开发问答stinct list from an existing list using LINQ? This is what I have so far and it is not distinct but does give me a new list.

Dim tmpQryColumn = (From a In _allAudits 
                    Select New CheckBoxListItem 
                    With {.Id = a.AuditColumn, .Name = a.AuditColumn} 
                    ).Distinct()
_columnList = New List(Of CheckBoxListItem)(tmpQryColumn)


I suspect the problem is that CheckboxListItem doesn't override Equals/GetHashCode so any two instances are effectively distinct. Try:

Dim columns = (From a In _allAudits
               Select a.AuditColumn).Distinct()

_columnList = (From column in columns
               Select New CheckBoxListItem 
               With {.Id = column, .Name = column} 
               ).ToList()

I'm sure there's a simpler way of writing it in VB, but I'm not familiar enough with the syntax to write it. The C# version would be:

_columnList = _allAudits.Select(x => x.AuditColumn)
                        .Distinct()
                        .Select(x => new CheckboxListItem { Id = x, Name = x })
                        .ToList();


The Distinct extension method relies on the types in question properly implementing value equality. The most likely reason that it's failing here is that CheckBoxListItem doesn't implement equality based on the Id and Name properties.

To fix this do one of the following

  1. Implement equality semantics for CheckBoxListItem
  2. Create an IEqualityComparer<CheckBoxListItem> and use the overload of Distinct which takes that value
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜