从对象列表获取属性列表


88

目前,我使用foreach循环返回object属性列表。

 class X
 {
     List<X> Z = GetXlist();
     List<String> r = new List<String>();

     foreach (var z in Z)
     {
         r.Add(z.A);
     }

     return r;
}

有没有一种方法可以缩短此时间,从而不必编写foreach循环?


您不是在编写for循环。您应该意识到程序员之间
Darren Young

Answers:


166

LINQ就是答案。您可以使用它从对象集合“投影”到另一个集合-在这种情况下,是对象属性值的集合。

List<string> properties = objectList.Select(o => o.StringProperty).ToList();

12

您可以使用LINQ:

List<X> Z = GetXlist();

List<String> r = Z.Select(z => z.A).ToList();

return r;

要不就,

return GetXlist().Select(z => z.A).ToList();

了解有关LINQ的更多信息。这非常有用。


0
List<string> properties = objectList.Select(o => o.StringProperty).ToList();

您还可以通过私有OverLoading方法来做,并在LINQ查询中使用它。


4
这不会为已确定的答案提供价值
Ivan Kaloyanov
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.