Which LINQ query can be used to return the maximum total Quantity?

Considering that the attached table is stored in a variable called "dt":

Which LINQ query can be used to return the maximum total Quantity?
A . dt.AsEnumerable. Max(Function(x) Convert.ToInt32(x("Quantity").ToString))
B . dt.AsEnumerable. Max(Function(x) Convert.ToInt32(x("Quantity").ToString))("Item")
C . dt.AsEnumerable. GroupBy(Function(x) x("Item").ToString). Max(Function(x) x.Sum(Function(y) Convert.ToInt32(y("Quantity").ToString)))
D . dt.AsEnumerable. OrderByDescending(Function(x) Convert.ToInt32(x("Quantity").ToString)). First.Item("Quantity")

Answer: C

Explanation:

The LINQ query that can be used to return the maximum total Quantity from the attached table is dt.AsEnumerable. GroupBy(Function(x) x(“Item”).ToString). Max(Function(x) x.Sum(Function(y) Convert.ToInt32(y(“Quantity”).ToString))). This query uses the LINQ methods AsEnumerable, GroupBy, Max, and Sum to manipulate the data in the dt variable. The dt variable is a DataTable that contains the following data:

No. Item Quantity

The AsEnumerable method converts the DataTable into an Enumerable collection of DataRow objects. The GroupBy method groups the elements of the collection by the value of the Item column, creating a collection of groups. Each group has a key, which is the Item name, and a list of elements, which are the DataRows that have the same Item value. The Max method returns the maximum value of the collection, based on a selector function. The selector function is a lambda expression that calculates the sum of the Quantity column for each group. The Sum method returns the sum of the elements in a collection, based on a selector function. The selector function is a lambda expression that converts the value of the Quantity column into an integer. Therefore, the query will group the DataRows by the Item name, calculate the total Quantity for each group, and return the maximum total Quantity among the groups. The maximum total Quantity is 80, which corresponds to the group with the key “kiwi”.

Reference: [DataTable.AsEnumerable Method], [Enumerable.GroupBy Method], [Enumerable.Max Method], [Enumerable.Sum Method]

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments