简体   繁体   English

如何从集合中获取一个属性并将其分配给数组?

[英]How can I get one property from a collection and assign it to an array?

I thought this would be easy, but I can't seem to get it to work.我认为这很容易,但我似乎无法让它发挥作用。

I have a model in my Entity Framework project called _context.Galaxy.我在名为 _context.Galaxy 的实体框架项目中有一个 model。

It contains a bunch of different properties, but I only want to retrieve the name and create a string array of all the galaxy names in the database.它包含一堆不同的属性,但我只想检索名称并创建数据库中所有星系名称的字符串数组。

Here is my code:这是我的代码:

var allGalaxyNames = _context.Galaxy
    .Select(x => new
    {
        GalaxyName = x.Name.ToString()
    }).ToArray();


    string[] AllGalaxys = allGalaxyNames

I keep getting this error no matter what I try:无论我尝试什么,我都会不断收到此错误:

 Cannot implicitly convert type '<anonymous type: string GalaxyName>[]' to 'string[]'

How can I get this to work?我怎样才能让它工作?

Thanks!谢谢!

You don't need the anonymous object, just return a string from the Select .您不需要匿名 object,只需从Select返回一个字符串。

string[] allGalaxyNames = _context.Galaxy
    .Select(x => x.Name.ToString())
    .ToArray();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM