[英]Is there a way that I can set more than one property in a list to “” or null at the same time with a .ForEach?
我有這個有效的代碼,但我想簡化它。 我試圖將 each.ForEach 串在一起,但似乎這是不可能的。 有人可以建議我如何結合這些:
phraseSources
.ToList()
.ForEach(i => i.JishoExists = "");
phraseSources
.ToList()
.ForEach(i => i.CommonWord = "");
phraseSources
.ToList()
.ForEach(i => i.JishoWanikani = null);
phraseSources
.ToList()
.ForEach(i => i.JishoJlpt = null);
因為ForEach
第一個參數是Action<T>
這意味着您可以使用帶有一個參數的委托方法。
您可以嘗試在委托參數上使用大括號。
phraseSources
.ToList()
.ForEach(i => {
i.JishoExists = "";
i.CommonWord = "";
i.JishoWanikani = null;
i.JishoJlpt = null;
});
我認為foreach
(不是ForEach
)是這項工作的最佳工具。
foreach(var i in phraseSources)
{
i.JishoExists = "";
i.CommonWord = "";
i.JishoWanikani = null;
i.JishoJlpt = null;
}
ToList().ForEach
可能導致意外結果。 考慮以下示例。
public class XClass {public string A {get; set;}}
public struct XStruct {public string A {get; set;}}
public static void Main(string[] args)
{
var array1 = new []{new XClass{A="One"}, new XClass{A="Two"}};
var array2 = new []{new XStruct{A="One"}, new XStruct{A="Two"}};
array1.ToList().ForEach( x => x.A = "XXX");
array2.ToList().ForEach( x => x.A = "XXX");
Console.WriteLine(array2[0].A); // Ooops: it's still "One"
}
您可以創建一個新的 object:
phraseSources.Select(i => new NameOfYourObject {
JishoExists = "",
CommonWord = "",
JishoWanikani = null,
JishoJlpt = null,
// more properties here.
});
一個想法是使用構建器模式將其包裝到重置 function 中:
phraseSources.Select(i => i.Reset());
在您的 object 中添加此方法:
public NameOfYourObject Reset() {
JishoExists = "";
CommonWord = "";
JishoWanikani = null;
JishoJlpt = null;
// more properties here.
return this;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.