首页 > 解决方案 > C# 从列表中选择 id

问题描述

我想知道是否有比使用 for each 循环和字符串生成器更好的方法来选择列表对象中的 Id。

   class Program
{
    static void Main(string[] args)
    {
        List<Person> peopleList = new List<Person>();
        peopleList.Add(new Person() { ID = 1 });
        peopleList.Add(new Person() { ID = 2 });
        peopleList.Add(new Person() { ID = 3 });

        //string Ids = peopleList.Select(x => x.ID);
        StringBuilder Ids = new StringBuilder();
        foreach (var people in peopleList)
        {
            Ids.Append(people.ID);
            Ids.Append("-");
        }

        Console.WriteLine(Ids.ToString());
    }



    class Person
    {
        public int ID { get; set; }
    }
}

标签: c#list

解决方案


您可以使用SelectJoin

string.Join("-", peopleList.Select(x => x.ID))

在线试用

static void Main(string[] args)
{
    List<Person> peopleList = new List<Person>();
    peopleList.Add(new Person() { ID = 1 });
    peopleList.Add(new Person() { ID = 2 });
    peopleList.Add(new Person() { ID = 3 });


    Console.WriteLine(string.Join("-", peopleList.Select(x => x.ID)));
}

class Person
{
    public int ID { get; set; }
}

推荐阅读