我如何从List<ComplexObject>a 获得List<string>,假设ComplexObject有两个属性:类型为string的prop1和类型为int的prop2.我有兴趣提取一个List<string>(prop1列表).
举个例子,也许它更清楚.
想象一下,你有List<Country>Country是具有Id和Name的复杂对象.我有兴趣从countryList中提取一个名称列表,其中包含所有名称.
我知道我可以这样做:
List<string> nameList = new List<string>();
foreach (var country in countryList)
{
nameList.Add(country.Name);
}
Run Code Online (Sandbox Code Playgroud)
...但我想知道是否有更简单快捷的方法从countryList中提取nameList.也许与lambda或其他东西.
并且该字符串列表是否可以轻松转换为DataTable?
谢谢.
这是LINQ选择的常见用例,它将结果枚举转换为列表.这比做的更容易:
var nameList = countryList.Select(c => c.Name).ToList();
Run Code Online (Sandbox Code Playgroud)
转换为DataTable并没有如此方便地打包.这是关于这样做的答案.