C# 从对象列表中获取属性列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13781468/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 09:47:39  来源:igfitidea点击:

Get list of properties from List of objects

c#

提问by user1615362

Currently I use foreachloop to return a list of objectproperties.

目前我使用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;
}

Is there a way that I can shorten this so that I don't have to write the foreachloop?

有没有办法可以缩短它,这样我就不必编写foreach循环了?

采纳答案by Honza Brestan

LINQis the answer. You can use it to "project" from your object collection to another collection - in this case a collection of object property values.

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

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

回答by rae1

You could use LINQ:

你可以使用 LINQ:

List<X> Z = GetXlist();

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

return r;

Or just,

要不就,

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

Find out more about LINQ. It is prettyuseful.

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

回答by Anshuman

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

You Also Can Do By Private OverLoadingMethod and Use That in LINQ Query.

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