1

I am trying to convert object to a string using SelectMany. However when list property value is empty then I am not getting desired string.

I am expecting results like

name1-2-4 : name2-

but getting this result as

name1-2-4

. The second name is ignored because of "Scores" list which is empty.

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

Edit: Based on @JonasH solution use this linq query.

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

2 Answers 2

1

A simple solution would be to add a helper method to your person that does what you want:

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

and use that instead of .Scores in SelectMany.

Sign up to request clarification or add additional context in comments.

2 Comments

unfortunately, not allowed to change those classes.
@PSR then just make it an extension method.
1
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}";

1 Comment

Welcome to StackOverflow. Please provide explanation as well not just code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.