C# 将列表中所有项目的字段设置为相同的值

标签 c#

因此,当您取回列表时,一个值由存储库填充,但您希望列表中的每一项都具有相同的值。感觉 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/

相关文章:

c# - 用两个相等的值序列化标志枚举

c# - 无法将 '&' 运算符应用于通用枚举参数

c# - 如何将所有文件编译成一个exe?

c# - 另存为使用 EPPlus?

c# - 显示数据库中的分层数据?

c# - 如何使用未知 T 从 ICollection<T> 获取计数

c# - WPF 项目中的 Serilog

c# - 如何只获取没有文件路径的文件名?

c# - ASP.NET MVC3 - 自定义验证属性 -> 客户端损坏

c# - 在 MVVM 应用程序中使用 autofac