C# Set field of all items in list to same value

Viewed 42479

So when you get back an list, one value is filled by the repository but the other you want to have the same value for each item in the list. It feels like an for each loop is the a lot of code for simple functionality. Is there a way to shorten the code.

So some context. This is an example class.

public class ExampleClass
{
    public string A { get; set; }
    public string B { get; set;
}

This is an method that works:

public IEnumerable<ExampleClass> GetAll(string bValue)
{
    var exampleList = repo.GetAll(); //Asume that the repo gives back the an list with A filled;
    var returnValue = new List<ExampleClass>();
    foreach (var item in exampleList)
    {
        item.B= bValue;
        returnValue.Add(item);
    }
    return returnValue;
}

It would be great if there could something like:

public IEnumerable<ExampleClass> GetAll(string bValue)
{
    return repo.GetAll().Map(i => i.B = bValue);
}

Does anyone knows something like this.

4 Answers

You could use yield return:

public IEnumerable<ExampleClass> GetAll(string bValue)
{
    foreach (var item in repo.GetAll())
    {
        item.B = bValue;
        yield return item;
    }
}

You can also turn this into an extension method for more fluency:

public static class IEnumerableExtensions
{
    public static IEnumerable<T> Map<T>(this IEnumerable<T> source, Action<T> action)
    {
        foreach (var item in source)
        {
            action(item);
            yield return item;
        }
    }
}

// usage
public IEnumerable<ExampleClass> GetAll(string bValue)
{
     return repo.GetAll().Map(x => x.B = bValue);
}
 return repo.GetAll().ToList().ForEach(i => i.B = bValue);

This should work. Not tested though.

I think you can use this approach:

return exampleList.Select(i => { i.B = bValue; return i; });
Related