HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Select Items from List using Array

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
arraylistitemsusingselectfrom

Problem

Is there a better way to write this procedure?

public List GetInventory(int[] denominations)
    {
        var inventory = new List();

        foreach (var denomination in denominations)
        {
            foreach (var item in Account)
            {
                if (item.Currency == denomination)
                {
                    inventory.Add(item);
                }
            }
        }

        return inventory;
    }

Solution

You could use some linq to do this fairly easily. Converting the array to a HashSet will allow Contains to operate faster

public List GetInventory(int[] denominations)
{
    var denoms = new HashSet(denominations);
    return Account.Where( a => denoms.Contains(a.Currency) ).ToList();
}


This assumes that Account : IDenomination though, as does your original code. If that were not the case, you would use a .Select() prior to .ToList() in order to select the IDenomination from Account.

Code Snippets

public List<IDenomination> GetInventory(int[] denominations)
{
    var denoms = new HashSet<int>(denominations);
    return Account.Where( a => denoms.Contains(a.Currency) ).ToList();
}

Context

StackExchange Code Review Q#82076, answer score: 7

Revisions (0)

No revisions yet.