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

时间:2017-09-25 17:59:53

标签: c#

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

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

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);
}

有谁知道这样的事情。

4 个答案:

答案 0 :(得分:5)

您可以使用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);
}

答案 1 :(得分:4)

 return repo.GetAll().ToList().ForEach(i => i.B = bValue);

这应该有效。虽然没经过测试。

答案 2 :(得分:4)

您可以尝试LINQ。根据这个链接: Update all objects in a collection using LINQ,你可以这样做:

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

然而,根据Jon Skeet的说法,最好只使用Foreach循环。 https://stackoverflow.com/a/7851940/5779825

答案 3 :(得分:1)

我认为您可以使用这种方法:

return exampleList.Select(i => { i.B = bValue; return i; });