2017-09-25 52 views
1

因此,當您取回列表時,一個值由存儲庫填充,但另一個值要爲列表中的每個項目具有相同的值。感覺就像每個循環都有很多簡單功能的代碼。有沒有辦法縮短代碼。C#將列表中所有項目的字段設置爲相同的值

所以有些上下文。這是一個示例類。

public class ExampleClass 
{ 
    public string A { get; set; } 
    public string B { get; set; 
} 

這是工作的一個方法:

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

有誰知道這樣的事情:

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

如果有可能像這將是巨大的。

+0

只是有些看我的代碼現在我可以做這樣的事情。 'var allImages = new List (); allImages.ForEach(新行動((FileInfo的數據)=> { }));' –

+0

真映射函數只是的函數調用地圖的內部運行的每個循環是一個除外FUNC –

+0

你可以有一個泛型函數,你可以在其中指向一個屬性,並讓它動態地構建一個表達式來將該屬性設置爲一個值 –

回答

3

你可以使用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); 
} 
+0

是的,這個擴展方法從我的業務邏輯中抽取每個循環。謝謝。 –

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

這應該工作。雖然沒有測試過。

+0

'List .ForEach'是一個'void'函數 – Xiaoy312

+0

所以你需要一箇中間變量來存儲和返回列表 – Xiaoy312

+0

謝謝。 GetAll()後應該有一個ToList()。 –

相關問題