Linq将模型字符串组合到单个字符串中



尝试找到一种简单的方法,将字符串从几个模型组合到使用Linq到对象表达式的单个字符串中。试图将结果全部放在鲍勃的名称所在的第一个对象中,或者全部在People.Names位置。也许我需要添加另一种扩展方法,例如cocece?

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

可以做这样的事情:

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

您可以使用string.Join

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

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

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

不要忘记添加

using System.Linq;

仅用于娱乐版本

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

疯狂版本:

string.Concat(people.Zip(
                Enumerable.Range(0, people.Count).Select(x => " "),
                (p, s) => p.Name + s)).Trim()

最新更新