Pet*_*r H 0 c# arrays class object
我有以下类定义.
public class people
{
public string first_name { get; set; }
public string last_name { get; set; }
public DateTime date_of_birth { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
然后我创建了一系列人,如下所示:
people[] the_people = new people[3];
the_people[0].first_name="Tony";
the_people[0].last_name="Carrot";
the_people[0].date_of_birth=new DateTime(1959-03-16);
the_people[1].first_name="Joe";
the_people[1].last_name="Tomato";
the_people[1].date_of_birth=new DateTime(1963-06-2);
the_people[2].first_name="Tarina";
the_people[2].last_name="Wends";
the_people[2].date_of_birth=new DateTime(1982-11-22);
Run Code Online (Sandbox Code Playgroud)
如何将the_people对象的first_names存储在新的字符串数组中,以便获得如下所示的输出.这可能通过linq
string[] the_peoples_first_names=new string[3] {"Tony","Joe","Tarina"};
Run Code Online (Sandbox Code Playgroud)
类似地,我如何获得一个日期时间数组,以便将所有人的出生日期存储在单独的DateTime数组中.
您尝试做的事情可以通过LINQ完成.您基本上要求的是投影.
投影是指将对象转换为新形式的操作,该新形式通常仅包含随后将使用的那些属性.通过使用投影,您可以构造从每个对象构建的新类型.您可以投影属性并对其执行数学函数.您也可以在不更改原始对象的情况下投影.
因此,我们希望将the_people
数组中的对象投影到新数组中.文档建议使用Select
LINQ运算符:
var the_people_names = the_people.Select(p => p.first_name);
Run Code Online (Sandbox Code Playgroud)
其中的内容Select
是委托,通常以lambda表达式或匿名委托的形式出现.
但我们还没到那里.Select
只是一个延迟评估,它创建了一个可枚举的序列.它不返回数组.要创建数组,我们使用.ToArray()
:
var the_people_names_array = the_people.Select(p => p.first_name).ToArray();
Run Code Online (Sandbox Code Playgroud)
您可以将此方法用于people
课程的任何属性,包括出生日期.
您可以在LINQ about页面上了解有关MSDN上的LINQ的更多信息.