c# - 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; }
}
}
解决方案
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; }
}
推荐阅读
- c# - 我收到“输入字符串不是给定格式”错误,因为在我的文本文件中输入的 Id 值
- python - 每日 OLS 回归的 for 循环日期
- javascript - 查询 nodejs 承诺
- sql - 在 matillion ETL 中查找包含两个项目名称的列的运行总计
- crash - Q) 由于 CRYPTO_memcmp 中的内存冲突导致 openJ9 libcryp 崩溃
- ios - 屏幕中间的iOS标签栏
- flutter - Flutter:未处理的异常:FileSystemException:创建失败,路径='目录:''(操作系统错误:只读文件系统,errno = 30)
- python - Pykafka 客户端忽略 ssh/tls
- excel - VBA 从 Excel 关闭 PDF 文档
- javascript - 使用js删除链表中的重复项