c# – 使用Linq更新嵌套属性

前端之家收集整理的这篇文章主要介绍了c# – 使用Linq更新嵌套属性前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个具有非原始属性的类.
我需要更新父类属性的一些子属性. @H_403_3@public class Parent { public string Abc { get; set; } public Childclass Pos { get; set; } } public class Childclass { public string Value { get; set; } } List<Parent> parents = new List<Parent>() Parent p1 = new Parent(); p1.Pos.Value = "1"; parents.Add(p1); Parent p2 = new Parent(); p2.Pos.Value = "2"; parents.Add(p2);

现在我需要在Pos.Value ==“2”的父母那里更新Pos?

解决方法

@H_403_3@List<Parent> parents = new List<Parent>(); Parent p1 = new Parent(); p1.Pos = new Childclass() { Value = "1" }; parents.Add(p1); Parent p2 = new Parent(); p2.Pos = new Childclass() { Value = "2" }; parents.Add(p2);

如果您需要更新每个项目:

@H_403_3@foreach (Parent parent in parents.Where(e => e.Pos.Value.Equals("2"))) parent.Pos.Value = "new value";

如果您只需要更新第一项:

@H_403_3@parents.FirstOrDefault(e => e.Pos.Value.Equals("2")).Pos.Value = "new value";
原文链接:https://www.f2er.com/csharp/99377.html

猜你在找的C#相关文章