【问题标题】:Convert object to string using Linq使用 Linq 将对象转换为字符串
【发布时间】:2021-05-03 14:09:33
【问题描述】:

我正在尝试使用 SelectMany 将对象转换为字符串。但是,当列表属性值为空时,我没有得到想要的字符串。

我期待这样的结果

name1-2-4 : name2-

但是得到这个结果

名称1-2-4

。第二个名字被忽略,因为“Scores”列表是空的。

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

编辑: 基于@JonasH 解决方案,使用此 linq 查询。

var result = string.Join(" : ", persons.SelectMany(x=>GetNames(x)));

【问题讨论】:

    标签: c# linq


    【解决方案1】:

    一个简单的解决方案是为你的人添加一个帮助方法来做你想做的事:

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

    并在 SelectMany 中使用它而不是 .Scores

    【讨论】:

    • 很遗憾,不允许更改这些类。
    • @PSR 然后将其设为扩展方法。
    【解决方案2】:
    var result1 = persons.SelectMany(x => x.Scores, (parent, child) => parent.Name + "-" + child.InitialScore + "-" + child.UpdatedScore).FirstOrDefault();
    
    var result2 = persons.Where(x => x.Scores.Count() <= 0).Select(x => x.Name).FirstOrDefault()+"-";
                
    var result = $"{result1}:{result2}";
    

    【讨论】:

    • 欢迎来到 StackOverflow。请提供解释,而不仅仅是代码。
    猜你喜欢
    • 1970-01-01
    • 2018-05-04
    • 2013-04-15
    • 1970-01-01
    • 1970-01-01
    • 2014-01-14
    • 2011-08-02
    • 2016-06-10
    相关资源
    最近更新 更多