-2

I want to choose the media based on the size, but can't seem to figure out how to pick the one with lowest memory consumption in a smart way.

The memory usage is stored in the field Size.

using System;
using System.Collections.Generic;

struct placeholder
{
    string size;

    public placeholder(string input)
    {
        this.size = input;
    }
}

public class Program
{
    public static void Main()
    {
        List<placeholder> list = new List<placeholder>();
        list.Add(new placeholder("1"));
        list.Add(new placeholder("2"));
        list.Add(new placeholder("3"));
        list.Add(new placeholder("4"));

        // How to find the entry in list with lowest placeholder.size?
        Console.WriteLine("Hello World");
    }
}

But how do I pick the one with with the lowest memory, the size is stored as a string?

I could do it a for loop, but is there something smarter?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
anita
  • 193
  • 10

3 Answers3

3

There is nothing smarter than going through the list. Period.

It is a LIST - it has no inner magic knowledge about a special condition, so to find one matching a specific condition (lowest memory) you must go through all the elements and evaluate them. Period - intrinsic basic logic, nothing smart is possible here.

Take every element, compare the size to the size stored for the size of the smallest element and replace the smallest element if it is smaller (and define what to do on same size).

TomTom
  • 61,059
  • 10
  • 88
  • 148
2

You cannot avoid "visiting" each element of the entire list regardless of the solution you go with because in order to get the min item you're required to compare against every other item.

You can get the result via Linq Aggregate :

var min = list.Aggregate((l, r) => int.Parse(l.size) > int.Parse(r.size) ? r : l);

or use a typical for loop.

Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
0

Typical solution for this problem is sorting the list then taking the first or last item depending on your sort algorithm.

M.Hazara
  • 137
  • 9