Count elements of an array only using Linq?

Related searches

I have the 3 classes Item, Order and Management. Order has an array with ordered Items, Management has a List of different Orders. How can I display the number of ordered items for all PurchaseOrders with the given name?

For example: Item1 is ordered 2 times with quantity = 5 and 2 times with quantity = 7, so the total number is 2*5+2*7=24.

I can solve the task, but only Linq should be used without loops, etc.

class MainClass
{
    public static void Main(string[] args)
    {
        Management Management = new Management();
        Management.PrintQuantityForSingleItem("Item1");
    }
}

class Item
{
    public string Name { get; set; }
    public decimal Price { get; set; }
    public int Quantity { get; set; }

    public Item(string Name, decimal Price, int Quantity)
    {
        this.Name = Name;
        this.Price = Price;
        this.Quantity = Quantity;
    }
}

class Order
{
    public int Id { get; set; }
    public Item[] Items { get; set; }

    public Order(int Id, Item[] Items)
    {
        this.Id = Id;
        this.Items = Items;
    }
}

class Management
{
    public List<Order> Orders { get; set; }

    public Management()
    {
        Item i1 = new Item("Item1", 2.0M, 5);
        Item i2 = new Item("Item2", 3.0M, 6);
        Item i3 = new Item("Item1", 2.0M, 7);

        Orders = new List<Order>()
        {
            new Order(1, new Item[]{i1, i2}),
            new Order(2, new Item[]{i3}),
            new Order(3, new Item[]{i1, i3}),
        };
    }

    //displays the total number of ordered items for all Orders with the given name on the console.
    public void PrintQuantityForSingleItem(string itemName)
    {
        var result = (from x in Orders
                      select x.Items).ToList();

        int counter = 0;
        for (int i = 0; i < result.Count(); i++)
        {
            for (int a = 0; a < result[i].Count(); a++)
            {
                if (result[i][a].Name == itemName)
                {
                    counter = counter + result[i][a].Quantity;
                }
                Console.WriteLine(result[i][a].Name);
            }
        }
        Console.WriteLine(itemName + " " + counter);//for example: shows 24 for item1
    }
}

Welcome to SO. It is obviously not advisable to look up items by name, but ignoring aspects of the design, here is one way of doing it:

var result = Orders.SelectMany(i => i.Items)
    .Where(i => i.Name == itemName)
    .Sum(i => i.Quantity);

Console.WriteLine($"{itemName}: {result}"); //24

Output:

Item1: 24

C# Count Elements in Array and List, This is a LINQ extension method—it can be confusing if you don't know the difference. CountIEnumerable. C# program that uses List using System; using System. LINQ Count - counts number of items in a collection (result type is Int32) LINQ LongCount - counts number of items in a collection (result type is Int64) LINQ Average - computes average value of numeric collection; LINQ Aggregate - applies aggregate function to a collection; C# List - illustrative examples of all List<T> methods

You'll need to select all order items, group them by name and then calculate the sum value for the Quantity. The final step is to get the calculated sum value by item name and display it

public void PrintQuantityForSingleItem(string itemName)
{
    var results = Orders
        .SelectMany(o => o.Items)
        .GroupBy(i => i.Name)
        .Select(g => new { Item = g.Key, Sum = g.Sum(i => i.Quantity) });

    var item = results.FirstOrDefault(r => r.Item.Equals(itemName, StringComparison.OrdinalIgnoreCase));

    Console.WriteLine(itemName + " " + item?.Sum);//shows 24 for item1
}

LINQ Count, Commented Enumerable.Count implementation. ➤ int result = list.Count(); LINQ query expression to count number of all items in the collection. ICollection<T> is implemented by List<T>, Dictionary<T>, HashSet<T>, array T[] and others. We can pick the nth item from an integer array using LINQ . It's just like picking an element of an array using an index. We need to use the ElementAt(n) function to point to the nth element. static void Main(string [] args) { int [] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 ,5,1}; var lowNums = (from n in numbers select n).ElementAt(2);

You can try the following,

public void PrintQuantityForSingleItem(string itemName)
    {
        var res = Orders.Select(x=>x.Items).Sum(y => y.Where(z => z.Name == itemName).Sum(t => t.Quantity));
        Console.WriteLine(res);
        Console.ReadKey();
    }

It prints 24

Count - Using C# LINQ - A Practical Overview, The LINQ methods in this chapter examine the elements of an IEnumerable<T> sequence and return a result based on the examined values. For most of the� For an array, we need to use Length (not Count). In programs, an array's size is set differently than List or ArrayList. The size does not grow dynamically.Array Length Array. Last element: We use the Length property on arrays, and also the Count property on ArrayList and List, to access the final element.

You can use Linq :

decimal counter = Orders
    .SelectMany(o => o.Items)
    .Where(i => i.Name == itemName)
    .Sum(i => i.Quantity);

I hope you find this helpful.

Count elements of an array only using Linq?, er and Management. Order has an array with ordered Items, Management has a List of different Orders. How can I display the number of� Count elements of an array only using Linq? Ask Question Asked 4 months ago. Active today. Viewed 153 times -1. I have the 3 classes Item, Order and Management.

What's the use of .Any() in a C# List<>?, Also, if you're using Count() (the LINQ extension method for IEnumerable), what the count is, and just want to know if there are any items in the collection. Count distinct elements after adding each element of First Array with Second Array; Maximize count of distinct elements possible in an Array from the given operation; Count distinct median possible for an Array using given ranges of elements; Count subarrays having total distinct elements same as original array

Methods - Calculating a single value. The LINQ methods in this chapter examine the elements of an IEnumerable<T> sequence and return a result based on the examined values. . For most of the methods we will discuss, this returned result will be either a bool or an

Returns the only element of a sequence that satisfies a specified condition, and throws an exception if more than one such element exists. Single<TSource>(IEnumerable<TSource>) Returns the only element of a sequence, and throws an exception if there is not exactly one element in the sequence.

Comments
  • group by + sum? where is the problem?
  • Does this answer your question? Linq: GroupBy, Sum and Count
  • You can find a description of the various LINQ operators here. Each description comes with various examples.
  • Your solution helps me a lot, I changed it to query syntax and it works:)
  • @VanillaBigThundr I am glad you found it helpful!
  • This is correct, but I'm not a fan of using underscore like this as it usually means the parameter is going to be ignored.
  • @juharr IMO, it's just for simplicity:) I can update the code, of course
  • The OP himself has stated the result should be 24. Also, The method needs to return quantity (as stated on its name), not total.
  • I'm not downvoting, but you don't have to multiply price and quantity, just sum a quantity
  • I withdrew my downvote after you updated your answer. However, The code is still inefficient. Linq has methods that combine some of these operations. See my answer below.
  • thank you @JuanR , i consider your answer. i am afk , i will try your answer as soons as possible. At the moment, voted you
  • The Distinct is not needed and will cause the result to be wrong since the OP is reusing the same Item objects in multiple Order lists. Also they wanted the Quantity, not the total price.