linq将模型字符串组合成单个字符串

时间:2017-09-18 18:29:52

标签: c# linq

尝试找到一种简单的方法,使用linq到对象表达式将来自多个模型的字符串组合成单个字符串。试图将结果全部放在bob名称所在的第一个对象中,或者全部放在People.names位置。也许我需要添加另一种扩展方法,比如coalesce?

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace ConsoleApp3
{
    class Program
    {
        static void Main(string[] args)
        {
            People people = new People
            {
                Persons = 
                {
                    new Person{
                        Name = "Bob",
                        Age = 15
                    },
                    new Person{
                        Name = "James",
                        Age = 17
                    },
                    new Person{
                        Name = "Mary",
                        Age = 15
                    }
                },
            };

            people.names = people.Persons.Select(p => p.Name).ToList().ToString();
            Console.WriteLine(people.names);

        }
    }

        public class Person
        {
            public string Name { get; set; }
            public int Age { get; set; }
        }

        public class People
        {
            public People() {
                Persons = new List<Person>(); 
            }
            public string names { get; set; }   
            public IList<Person> Persons { get; set; }

        }

}

4 个答案:

答案 0 :(得分:2)

可以这样做:

class People
{
    public List<Person> Persons { get; set; }
    public string Names
    {
        get
        {
            if (Persons != null)
            {
                return String.Join(",", Persons.Select(p => p.Name));
            }
            else 
            {
                return string.Empty;
            }
        }
    }
}

class Person
{
    public string Name { get; set; }
}

答案 1 :(得分:1)

您可以使用string.Join

Console.WriteLine(String.Join(" ",people.Persons.Select(p => p.Name)));

答案 2 :(得分:1)

您可以使用string.Join使用分隔符连接多个字符串。要加入名称,请使用简单的选择:

string joinedNames = string.Join(",", people.Persons.Select(p => p.Name));

别忘了添加

using System.Linq;

答案 3 :(得分:1)

仅限有趣的版本

colors

疯狂版:

people.Aggregate("", (a, b) => $"{a} {b.Name}").Trim()
string.Concat(people.Select(p => p.Name + " ")).Trim()