C# 使用Linq将对象转换为字符串

C# 使用Linq将对象转换为字符串,c#,linq,C#,Linq,我正在尝试使用SelectMany将对象转换为字符串。然而,当列表属性值为空时,我并没有得到所需的字符串 我期待这样的结果 名称1-2-4:名称2- 但是得到这个结果 姓名1-2-4 。第二个名称被忽略,因为“分数”列表为空 using System; using System.Linq; using System.Collections.Generic; public class Program { public static void Mai

我正在尝试使用SelectMany将对象转换为字符串。然而,当列表属性值为空时,我并没有得到所需的字符串

我期待这样的结果

名称1-2-4:名称2-

但是得到这个结果

姓名1-2-4

。第二个名称被忽略,因为“分数”列表为空

using System;
using System.Linq;
using System.Collections.Generic;
                    
public class Program
{
    public static void Main()
    {
        var person1 = new Person()
        {
            Name = "name1",
            Scores = new List<Score>
            {
                new Score
                {
                    InitialScore =2,
                    UpdatedScore = 4
                }
            }
        };

        var person2 = new Person()
        {
            Name = "name2",
            Scores = new List<Score>()
        };

        var persons = new List<Person>();
        persons.Add(person1);
        persons.Add(person2);       
                
        var result = string.Join(" : ", persons.SelectMany(x=>x.Scores, (parent, child)=> parent.Name + "-" + child.InitialScore +"-"+ child.UpdatedScore));
        Console.WriteLine(result);
    }
}

public class Person
{
    public string Name {get; set;}
    public List<Score> Scores {get; set;}
}

public class Score
{
    public int InitialScore {get; set;}
    public int UpdatedScore {get; set;}
}

一个简单的解决方案是为您的人员添加一个帮助器方法,该方法可以执行您想要的操作:

    public static IEnumerable<string> GetNames(this Person p)
    {
        if (p.Scores.Count == 0)
        {
            yield return p.Name;
        }
        else
        {
            foreach (var score in p.Scores)
            {
                yield return $"{p.Name}-{score}";
            }
        }
    }
公共静态IEnumerable GetNames(此人p)
{
如果(p.Scores.Count==0)
{
收益率返回p.Name;
}
其他的
{
foreach(p.分数中的var分数)
{
产生返回$“{p.Name}-{score}”;
}
}
}
并在SelectMany中使用它而不是
.Scores

var result1=persons.SelectMany(x=>x.Scores,(parent,child)=>parent.Name+“-”+child.initialscores+“-”+child.UpdatedScore)。FirstOrDefault();
var result2=persons.Where(x=>x.Scores.Count()x.Name).FirstOrDefault()+“-”;
var result=$“{result1}:{result2}”;

很遗憾,不允许更改这些类。@PSR然后将其作为扩展方法。欢迎使用StackOverflow。请提供解释,而不仅仅是代码。
    public static IEnumerable<string> GetNames(this Person p)
    {
        if (p.Scores.Count == 0)
        {
            yield return p.Name;
        }
        else
        {
            foreach (var score in p.Scores)
            {
                yield return $"{p.Name}-{score}";
            }
        }
    }