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

C. *_*ijk 3 c#

因此,当您返回列表时,存储库会填充一个值,但另一个值要为列表中的每个项目具有相同的值.对于每个循环而言,感觉就像是用于简单功能的大量代码.有没有办法缩短代码.

所以有些背景.这是一个示例类.

public class ExampleClass
{
    public string A { get; set; }
    public string B { get; set;
}
Run Code Online (Sandbox Code Playgroud)

这是一种有效的方法:

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;
}
Run Code Online (Sandbox Code Playgroud)

如果有类似的东西会很棒:

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

有谁知道这样的事情.

oop*_*zie 8

你可以试试 LINQ。根据此链接: 使用 LINQ 更新集合中的所有对象,您可以执行以下操作:

repo.getAll().Select(c => {c.B = value; return c;}).ToList();
Run Code Online (Sandbox Code Playgroud)

但是,根据 Jon Skeet 的说法,最好只使用 Foreach 循环。 /sf/answers/549635831/

  • 我同意 Jon Skeet 的观点,你应该为每个循环使用一个,而不是 LINQ。但我只是不希望我的业务逻辑中的 for each 循环保持代码干净。 (2认同)

Xia*_*312 6

你可以使用yield return:

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

您还可以将其转换为更加流畅的扩展方法:

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);
}
Run Code Online (Sandbox Code Playgroud)


Ram*_*tap 5

 return repo.GetAll().ToList().ForEach(i => i.B = bValue);
Run Code Online (Sandbox Code Playgroud)

这应该工作。虽然没有测试。