Module
Module1
Sub
Main()
BasicExample()
Console.ReadLine()
End
Dim
InputString
As
String
=
"T0*A1?0*23aTA3 4T4\+a4 ?407#?A*6T+"
characterGroup =
(
From character
In
InputString.ToCharArray()
Group characterElement = character By charElement = character Into Group
Select
New
With
{.Character = charElement, .Occurrences = Group.Count}
).
ToList.
OrderBy(
Function
(anonymous) anonymous.Character)
Console.WriteLine($
"Char Occurrences"
)
For
Each
currentItem
characterGroup
"[{currentItem.Character}] {currentItem.Occurrences,5}"
Next
results = (From c
InputString.ToCharArray() Group c By c Into Group
{.Item = c, .Occurrences = Group.Count}).ToList.OrderBy(
(x) x.Item)
"{currentItem} - {currentItem.Character.GetType()} - {currentItem.Occurrences.GetType()}"
Public
Class
OccurrenceContainer
Property
Character()
Char
Occurrences()
Integer
Overrides
ToString()
Return
$
"{Character} {Occurrences}"
BasicExampleStrongTyped()
IOrderedEnumerable(Of OccurrenceContainer)
IOrderedEnumerable(Of OccurrenceContainer) =
Console.WriteLine(
BasicWordExample()
wordList =
List(Of
) From {
"Hello"
,
"Goodnight"
"Good"
"Last"
}
wordGroup =
From word
wordList
Group wordElement = word By token = word Into Group
{.Word = token, .Occurrences = Group.Count}
(anonymous) anonymous.Word)
currentWord
wordGroup
"{currentWord.Word}, {currentWord.Occurrences}"
WordOccurrenceContainer
Word()
"{Word} {Occurrences}"
WordExampleStrongTyped()
IOrderedEnumerable(Of WordOccurrenceContainer)
IOrderedEnumerable(Of WordOccurrenceContainer) =
Person
Id()
FirstName()
LastName
City
Country
"{FirstName} {LastName}"
Student
Inherits
Year()
ExamScores
Namespace
Classes
Students
Shared
List()
List(Of Student)
studentList
studentList.Add(
Student()
{
.FirstName =
"Mary"
.LastName =
"Lee"
.Year = 2019,
.ExamScores =
) From {97, 72, 81, 60}})
"Jerry"
"Foster"
) From {75, 84, 91, 39}})
"Chris"
"Scott"
.Year = 2020,
) From {88, 94, 65, 85}})
"Jason"
"Wong"
.Year = 2019, .ExamScores =
) From {97, 89, 85, 82}})
"James"
"Lang"
) From {35, 72, 91, 70}})
"Ming"
) From {55, 62, 95, 75}})
"Karen"
.Year = 2020, .ExamScores =
) From {45, 82, 81, 80}})
"Edward"
) From {55, 72, 81, 90}})
"Smith"
) From {75, 77, 91, 80}})
students = PersonLibrary.Classes.Students.List()
queryLastNames =
From student
students
Group By LastName = student.LastName Into studentGroup = Group
Where studentGroup.Count() > 1
Order By LastName
queryLastNames
Console.WriteLine(currentItem.LastName)
student
currentItem.studentGroup
" {student}"
StudentContainer1
LastName()
IEnumerable(Of Student)
EnumerationOfStudentContainer
IEnumerable(Of StudentContainer1) =
queryLastNames.
(item)
{.LastName = item.LastName, .List = item.studentGroup})
"{currentItem.LastName}"
currentItem.List
.LastName = item.LastName,
.List = item.studentGroup})
Where studentGroup.Count() > 1 Order By LastName).
A common requirement is to obtain count, totals, min, max and averages from a group by. The following example gets max orders for customer orders using Entity Framework where Orders is considered a navigation property of customers.
MaxOrdersByCountry(context
NorthWindContext)
maximumOrdersByCountry =
From customer
context.Customers
Group By customer.Country
Into MaxOrders = Max(customer.Orders.Count)
results = maximumOrdersByCountry.ToList()
item
results
"{item.Country.Name} - {item.MaxOrders}"
Group customer By customer.Country Into grouping = Group
Country.Name, MaxOrders = grouping.Max(
(x) x.Orders.Count)
MaxOrder
Country()
MaxOrders()
{.Country = Country.Name, .MaxOrders = grouping.Max(
(x) x.Orders.Count)}
List(Of MaxOrder) = maximumOrdersByCountry.ToList()
Imports
CategoryProductEntitiesLibrary.Models
ContainerClasses
ProductByCategory
Category()
Category
GroupCategoryProducts()
IGrouping(Of Category, Product)
Async
GroupProductByCategoryTask()
Task(Of List(Of ProductByCategory))
Using context
ProductContext
results = Await Task.Run(
()
context.Products.GroupBy(
(product) product.Category).
(group)
.Category = group.Key,
.GroupCategoryProducts = group
}).
ToListAsync()
Using
Private
GroupProductByCategoryButton_Click(sender
Object
, e
EventArgs) _
Handles
GroupProductByCategoryButton.Click
ListView1.Items.Clear()
productByCategories
List(Of ProductByCategory) = Await operations.GroupProductByCategoryTask()
group
ListView1.Items.Add(
ListViewItem(group.Category.CategoryName))
product
Product
group.GroupCategoryProducts
ListViewItem(
() {
""
, product.ProductName}))
Await Task.Delay(1)
TidyupListView()
ListView1.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize)
ListView1.EndUpdate()
ListView1.FocusedItem = ListView1.Items(0)
ListView1.Items(0).Selected =
True
ActiveControl = ListView1
GroupProductSortCategoryDescending()
List(Of GroupSortProduct)
IOrderedQueryable(Of GroupSortProduct)
'
' Here we are grouping by CategoryName under Products
' then creating a strong type for the select and within the select
' sorting the products by product name followed
' by sorting category, the key for the group in descending order.
results =
(product) product.Category.CategoryName).
GroupSortProduct
.CategoryName = group.Key,
.Products = group.OrderBy(
(prod) prod.ProductName)
OrderByDescending(
(group) group.CategoryName)
results.ToList()
CategoryName()
Products()
IOrderedEnumerable(Of Product)
ProductsGroupedSummed
TotalUnitsInStock()
?
ProductsGroupedSummed()
List(Of ProductsGroupedSummed)
productsGroupedSummedResults
categories = context.Products.GroupBy(
(productGroup)
Key .Category = productGroup.Key,
Key .TotalUnitsInStock = productGroup.Sum(
(p) p.UnitsInStock)
})
cat
categories
productsGroupedSummedResults.Add(
.Category = cat.Category.CategoryName,
.TotalUnitsInStock = cat.TotalUnitsInStock
AnonymousToStrongTypedVersion()
operations =
DataOperations
customers = operations.CustomerList()
baseQuery =
customers Order By customer.City
Group By CountryName = customer.Country Into regionalCustomers = Group
Order By CountryName
customersByCountry
IEnumerable(Of CountryCompanyContainer) =
baseQuery.
(customer)
CountryCompanyContainer
.CountryName = customer.CountryName,
.Customers = customer.regionalCustomers,
.Count = customer.regionalCustomers.Count()
TopGroup
"{TopGroup.CountryName} ({TopGroup.Count})"
innerGroup
TopGroup.Customers
"{innerGroup.CustomerIdentifier,5} {innerGroup.CompanyName} ({innerGroup.City})"
CustomersDataTableGrouping()
customers = operations.CustomerDataTable()
customers.AsEnumerable()
Order By customer.Field(Of
)(
"City"
Group By CountryName = customer.Field(Of
"Country"
) Into regionalCustomers = Group, Count()
customersByCountry =
CountryCompanyDataTableContainer
container
"{container.CountryName} ({container.Count})"
dataRow
DataRow
container.Customers
" {dataRow.Values()}"
System.Runtime.CompilerServices
DataExtensions
<Extension>
Values(sender
DataRow)
.Join(
","
, sender.ItemArray)
NameSpace