因此,当您取回列表时,一个值由存储库填充,但您希望列表中的每一项都具有相同的值。感觉 for each 循环是简单功能的大量代码。有没有办法缩短代码。
所以一些上下文。这是一个示例类。
public class ExampleClass
{
public string A { get; set; }
public string B { get; set;
}
这是一个有效的方法:
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;
}
如果能有这样的东西就好了:
public IEnumerable<ExampleClass> GetAll(string bValue)
{
return repo.GetAll().Map(i => i.B = bValue);
}
有没有人知道这样的事情。
最佳答案
你可以使用yield return
:
public IEnumerable<ExampleClass> GetAll(string bValue)
{
foreach (var item in repo.GetAll())
{
item.B = bValue;
yield return item;
}
}
你也可以把它变成一个更流畅的扩展方法:
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);
}
关于C# 将列表中所有项目的字段设置为相同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46411420/