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.
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);
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With