C# 是否有一种方法可以将列表中的多个属性设置为"&引用;或者与.ForEach同时为null?

C# 是否有一种方法可以将列表中的多个属性设置为"&引用;或者与.ForEach同时为null?,c#,C#,我有这个代码,但我想简化它。我试着把每一个都串在一起,但似乎不可能。有人能建议我如何将这些结合起来: phraseSources .ToList() .ForEach(i => i.JishoExists = ""); phraseSources .ToList() .ForEach(i => i.Common

我有这个代码,但我想简化它。我试着把每一个都串在一起,但似乎不可能。有人能建议我如何将这些结合起来:

            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
,这意味着您可以使用带有一个参数的委托方法

phraseSources
    .ToList()
    .ForEach(i => {
        i.JishoExists = "";
        i.CommonWord = "";
        i.JishoWanikani = null;
        i.JishoJlpt = null;
    });
您可以尝试在委托参数上使用大括号

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

顺便说一句,ForEach():这对结构不起作用。我敢说,
ToList()。foreach
有点反模式。