|
-
Apr 27th, 2018, 05:08 PM
#1
Thread Starter
Member
[RESOLVED] Select distinct column into list with LINQ AsEnumerable
This seems like it ought to work. In this code, intellisense has underlined "d_row.Field(Of String)" and flagged it with the warning:
'Field' is not a member of 'sites'.
So that means it is not recognizing 'Field' as a LINQ operator, it thinks I am trying to access a field named 'Field'.
What is my error?
The goal is to use LINQ to select a distinct column from a list of objects and place it in a list(of string).
Code:
Public Class sites
Public Property Name As String
Public Property Location As String
Public Sub New(n As String, l As String)
Name = n
Location = l
End Sub
End Class
Module Module1
Sub Main()
Dim sitelist As New List(Of sites)
For Each i As String In {"one", "one", "two", "three"}
Dim site As sites = New sites(i, "test")
sitelist.Add(site)
Next
Dim siterow As List(Of String) = (From d_row In sitelist.AsEnumerable()
Select d_row.Field(Of String)("Name")
Distinct).ToList
End Sub
End Module
-
Apr 27th, 2018, 08:46 PM
#2
Re: Select distinct column into list with LINQ AsEnumerable
Generic Lists don't have Fields that you access that way...
Code:
Dim siterow As List(Of String) = (From d_row In sitelist.AsEnumerable()
Select d_row.Name
Distinct).ToList
- Coding Examples:
- Features:
- Online Games:
- Compiled Games:
-
Apr 27th, 2018, 10:02 PM
#3
Re: Select distinct column into list with LINQ AsEnumerable
That Field(Of T) method you're using is an extension method and it is defined for the DataRow class only. It can be used specifically to get a field value from a DataRow. I'm guessing that that is where you saw it used because that AsEnumerable call is required to convert a DataTable into an IEnumerable(Of DataRow) but it's pointless in your case because a List(Of sites) is already an IEnumerable(Of sites).
By the way, 'sites' is a very bad name for that class. Firstly, all type names should start with an upper-case letter. Secondly, a type name should only be plural if it represents multiple objects, which is actually quite rare. In your case, the name should be 'Site' rather than 'sites'. Where the name 'sites' would be appropriate is for a variable that refers to a List(Of Site), because it does indeed represent multiple Site objects. A suitable variable name for a List(Of String) that contains the Name values of Site objects would be 'siteNames'.
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|