c# - 根据 List 的属性区分在一个班级里面
问题描述
class Parent
{
string Name;
string Description;
List<Child> Actions;
}
class Child
{
string Action;
string Value;
}
我有List<parent> parents
并且我想检索具有该类的不同Value
属性的父列表Action
。
我知道我可以使用parents.GroupBy(p => p.Actions).Select(f => f.First()).ToList()
,但它不起作用,因为它parent.Actions
是一个列表,我需要 Actions 中的不同属性值,所以parent.Actions.Value
.
输入:
List<Parent> parents =
parent1["name", "desc", Action["action", "uniqueAction1"]],
parent2["name", "desc", Action["action", "uniqueAction1"]],
parent3["name", "desc", Action["action", "uniqueAction2"]]
输出:
List<Parent> parents =
parent1["name", "desc", Action["action", "uniqueAction1"],
parent3["name", "desc", Action["action", "uniqueAction2"]]
它们都应该具有 的独特属性parent.Actions.Value
。
这是我没有 LINQ 的解决方案:
public List<Parent> FindUniqueParent()
{
List<Parent> newParent = new List<Parent>();
string previous = obj.Parents[0].Actions[0].Value;
newParent.Add(obj.Parents[0]);
for (int i = 1; i < obj.Parents.Count; i++)
{
if (obj.Parents[i].Actions[0].Value != previous && !newParent.Contains(obj.Parents[i]))
{
newParent.Add(obj.Parents[i]);
previous = obj.Parents[i].Actions[0].Value;
}
else
{
continue;
}
}
return newParent;
}
obj 是持有的对象,List<Parent> parents
父持有List<Child> child
。
如果其他人可以改进代码或有更好的解决方案,请告诉我!
解决方案
我不知道我是否完全得到你想要的,但我想你想在你的列表中的每个动作中检索“值”的字符串列表,对吗?好吧,您可以使用您提到的 GroupBy 方法检索列表,然后您可以创建一个新列表并循环遍历列表以填充您想要的值,如下所示:
List<Child> parentList = parent.GroupBy(p => p.Actions).Select(f => f.First()).ToList();
List<string> valuesList = new List<string>();
foreach(Child child in parentList)
{
valuesList.Add(child.Value);
}
因此,您的 valuesList 将是您父列表中所有值的列表