C# 在类中按列表的属性区分

C# 在类中按列表的属性区分,c#,linq,C#,Linq,输出: List<Parent> parents = parent1["name", "desc", Action["action", "uniqueAction1"]], parent2["name", "desc", Action["action", "uniqueAction1"]], parent3["n

输出:

List<Parent> parents = 
parent1["name", "desc", Action["action", "uniqueAction1"]],
parent2["name", "desc", Action["action", "uniqueAction1"]], 
parent3["name", "desc", Action["action", "uniqueAction2"]]
obj是包含列表父对象的对象,父对象包含列表子对象


如果其他人可以改进代码或有更好的解决方案,请让我知道

我不知道我是否完全得到了你想要的,但我想你想在列表中的每个操作中检索值的字符串列表,对吗?好的,您可以使用您提到的GroupBy方法检索列表,然后您可以创建一个新列表,并在列表中循环以填充所需的值,如下所示:

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

因此,您的valuesList将是父列表中所有值的列表

您的示例代码只查看parent.Actions属性中的第一项,因此我假设这就是您想要的。这会给你你想要的

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);
}
对于您的示例数据,这将给出:


欢迎-您可以显示预期的输入/输出吗?我添加了预期的输入和输出如果您在输入中切换parent2和parent3的顺序,您的代码将产生3个家长,这是您想要的吗?抱歉,请查看我的编辑以了解有关预期输入和输出的更多信息。
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;
}
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);
}
public List<Parent> FindUniqueParent()
{
    return obj.Parents.GroupBy(p => p.Actions[0].Value, (key, groups) => groups.FirstOrDefault())
           .ToList();
}