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

Guarantee at least one in a list

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

Problem

This is a short piece of code but I feel like it could be done more elegantly. What am I missing?

The goal: if there are any items in a list, and none of them have a given property, set one of them to have that property.

static void GuaranteeAtLeastOne(IEnumerable list, Func getter, Action setter)
{
    if (list.Any() && !list.Any(getter))
    {
        setter(list.First());
    }
}

Solution

I wouldn't assume to go for the First, rather I'd have a Func predicate parameter which you pass to a .FirstOrDefault(predicate) and ?? it with .First()

Also, I'd verify IEnumerable != null before anything.

static void GuaranteeAtLeastOne(IEnumerable list, Func getter, Action setter, Func predicate)
{
    if (list == null || list.Count == 0 || list.Any(getter))
    {
        return;
    }

    setter(list.FirstOrDefault(predicate) ?? list.First());
}

Code Snippets

static void GuaranteeAtLeastOne<T>(IEnumerable<T> list, Func<T,bool> getter, Action<T> setter, Func<T,bool> predicate)
{
    if (list == null || list.Count == 0 || list.Any(getter))
    {
        return;
    }

    setter(list.FirstOrDefault(predicate) ?? list.First());
}

Context

StackExchange Code Review Q#3802, answer score: 4

Revisions (0)

No revisions yet.