Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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.

like image 605
C. Molendijk Avatar asked Sep 25 '17 17:09

C. Molendijk


2 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);
}
like image 69
Xiaoy312 Avatar answered Oct 10 '22 21:10

Xiaoy312


You can try LINQ. According to this link: Update all objects in a collection using LINQ , you can do this:

repo.getAll().Select(c => {c.B = value; return c;}).ToList();

However, according to Jon Skeet, it's better to just use Foreach loop. https://stackoverflow.com/a/7851940/5779825

like image 23
oopsdazie Avatar answered Oct 10 '22 21:10

oopsdazie