Tag Archives: LINQ0

LINQ Basic DataSource binding

This is a quick example of LINQ and binding to a DataGridView control (via DataSource) the property name is used as the column header (Column[idx].HeaderText) this can be change via the following attribute:
System.ComponentModel.DisplayName(“Column header name here”)

The following example uses a LINQ query on a string collection to demonstrate this:

C#

var objCollection = from objs in fileStringCollection
                    select new WrapperForStrings
                    {StringProperty = objs};
this.DataGridView2.DataSource = objCollection.ToList();
this.DataGridView2.AutoResizeColumns();
...
public class WrapperForStrings
{
    private String stringValue;

    [System.ComponentModel.DisplayName("Column header name here C#")]
    public String StringProperty
    {
        get
        {
            return stringValue;
        }
        set
        {
            stringValue = value;
        }
    }
}

VB.NET

Dim objCollection = From objs In fileStringCollection _
                    Select New WrapperForStrings _
                    With {.StringProperty = objs}
Me.DataGridView2.DataSource = objCollection.ToList()
Me.DataGridView2.AutoResizeColumns()
...
Public Class WrapperForStrings
    Private stringValue As String

    <System.ComponentModel.DisplayName("Column header name here VB")> _
    Public Property StringProperty() As String
        Get
            Return stringValue
        End Get
        Set(ByVal value As String)
            stringValue = value
        End Set
    End Property
End Class

LINQ Basic Selects

Whether a select is required or not

VB.NET

' Notice no select is required
Dim fileStringCollection = From anythingGoesHere _
                           In My.Computer.FileSystem.GetFiles("C:\")

C#

// Select is required
var fileStringCollection = from anythingGoesHere
                           in Directory.GetFiles(@"C:\")
                           select anythingGoesHere;

Selecting into an object / properties

VB.NET

Dim objCollection = From objs _
                    In fileStringCollection _
                    Select New WrapperForStrings _
                      With {.StringProperty = objs}

C#

var objCollection = from objs
                    in fileStringCollection
                    select new WrapperForStrings
                      {StringProperty = objs};

Returning multiple columns (via an instance of an anonymous class) in a select

VB.NET

' VB can just use a plain syntax as follows
Dim myInfoCollection = From file In filesInfoCollection _
                       Select file.Name, file.CreationTime

C#

// In C# you must explicitly create a new (anonymous) object and explicitly define the properties and values
var myInfoCollection = from file in filesInfoCollection
                       select new { CSName = file.Name,
                         CSCreationTime = file.CreationTime };

Edit: For an example of WrapperForStrings see this post