.NET Core  

Data View and LINQ in C# and VB.NET

Data View and LINQ (Language-Integrated Query) with DataTable Query will be explored here for fetching unique values from the Database, along with a base class example.LINQ will work in .NET Core 3.1, .NET 5, .NET 6, and the latest version, .NET 9. We will have a Book Class example and retrieve the data from a DataTable to a DataView. The model-based class example is given below.

Book.cs

public class Book
{
    public int BookID { get; set; }    
    public string Title { get; set; }    
    public string Author { get; set; }   
    public string Genre { get; set; } 
    public decimal Price { get; set; }
}

Book Class Output Example without using LINQ.

BookID Title Author Genre Price
1 XXX xxx 1.1 45.00
2 YYY yyy 2.1 45.00
3 ZZZZ zzz 1.1 50.00
4 AAA aaa 1.1 30.00

To retrieve the unique values of the version sorted by price value, the example code below is provided for C# and VB.NET.

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        List<Book> books = new List<Book>
        {
            new Book { BookID = 1, Title = "XXX", Author = "xxx", version = "1.1", Price = 45.00m },
            new Book { BookID = 2, Title = "YYY", Author = "yyy", version = "2.1", Price = 50.00m },
            new Book { BookID = 3, Title = "ZZZZ Hobbit", Author = "zz", version = "1.1", Price = 30.00m },
            new Book { BookID = 4, Title = "AAA", Author = "aa", version = "1.1", Price = 42.00m }
        };

        // LINQ: Get all 1.1 books sorted by price 
        var programmingBooks = books
            .Where(b => b.version == "1.1")
            .OrderBy(b => b.Price);

        Console.WriteLine("Books (sorted by price):");
        foreach (var book in programmingBooks)
        {
            Console.WriteLine($"{book.Title} by {book.Author} - ${book.Price}");
        }
    }
}

class Book
{
    public int BookID { get; set; }
    public string Title { get; set; }
    public string Author { get; set; }
    public string version { get; set; }
    public decimal Price { get; set; }
}
Dim bookTable As New DataTable()
bookTable.Columns.Add("BookID", GetType(Integer))
bookTable.Columns.Add("Title", GetType(String))
bookTable.Columns.Add("Author", GetType(String))
bookTable.Columns.Add("Genre", GetType(String))
bookTable.Columns.Add("Price", GetType(Decimal))

' Sample data
bookTable.Rows.Add(1, "XXX", "xxx", "1.1", 45.0D)
bookTable.Rows.Add(2, "YYY", "yyy", "1.2", 45.0D)
bookTable.Rows.Add(3, "ZZZ", "zzz", "2.1", 50.0D)
bookTable.Rows.Add(4, "AAA", "aa", "1.1", 30.0D)

Dim view As New DataView(bookTable)
Dim distinctBooks As DataTable = view.ToTable(True, "Title", "Author")

For Each row As DataRow In distinctBooks.Rows
    Console.WriteLine($"Title: {row("Title")}, Author: {row("Author")}")
Next

Output

Title: XXX, Author: xxx
Title: ZZZZ, Author: zz
Title: AAA, Author: aa