Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Finding element in List of String Arrays

Tags:

c#

I cannot solve a problem for several hours now. Here is a simplified scenario. Let's say there is a list of people with their bids. I'm trying to find a person with the highest bid and return the name. I am able to find the highest bid, but how to I output the name?

        List<String[]> list = new List<String[]>();
        String[] Bob = { "Alice", "19.15" };
        String[] Alice = {"Bob", "28.20"};
        String[] Michael = { "Michael", "25.12" };

        list.Add(Bob);
        list.Add(Alice);
        list.Add(Michael);

        String result = list.Max(s => Double.Parse(s.ElementAt(1))).ToString();

        System.Console.WriteLine(result);

As a result I get 28.20, which is correct, but I need to display "Bob" instead. There were so many combinations with list.Select(), but no success. Anyone please?

like image 795
Alex Avatar asked Nov 29 '22 09:11

Alex


2 Answers

The best solution from an architectural point of view is to create a separate class (e.g. Person) that contains two properties Name and Bid of each person and a class Persons that contains the list of persons.

Then you can easily use a LINQ command.

Also instead of storing bids as string, think if bids as floating point or decimal values would be better (or store it in cents and use an int).

I don't have a compiler by hand so it's a bit out of my head:

public class Person
{
    public string Name { get; set; }
    public float  Bid  { get; set; }

    public Person(string name, float bid)
    {
        Debug.AssertTrue(bid > 0.0);
        Name = name;
        Bid = bid;
    }
}

public class Persons : List<Person>
{
    public void Fill()
    {
        Add(new Person("Bob", 19.15));
        Add(new Person("Alice" , 28.20));
        Add(new Person("Michael", 25.12));
    }
}

In your class:

var persons = new Persons();
persons.Fill();

var nameOfHighestBidder = persons.MaxBy(item => item.Bid).Name;
Console.WriteLine(nameOfHighestBidder);
like image 186
Michel Keijzers Avatar answered Dec 18 '22 07:12

Michel Keijzers


This works in the simple example. Not sure about the real one

var result = list.OrderByDescending(s => Double.Parse(s.ElementAt(1))).First();
like image 27
Juan Ayala Avatar answered Dec 18 '22 08:12

Juan Ayala