1

I want to select multiple fields from a list. This is my code:

string[] NamesArray = Users
            .Select(i => new {  i.FirstName, i.LastName })
            .Distinct()
            .OrderByDescending(i => i.FirstName)
            .ToArray();

When I use this code the error is: 'Cannot implicitly convert type 'anonymous type: string FirstName, string LastName []' to string[]' What can I do???

1 Answers1

1

That is because of anonymous select so when you select like (i => new { i.FirstName, i.LastName }) it will give you a list of object that each of object have FirstName and LastName which is not string and can't be cats to string.

so you should do something like this:

string[] NamesArray = Users.OrderByDescending(i => i.FirstName)
         .Select(i => i.FirstName + " " + i.LastName)
         .Distinct()
         .ToArray();

if you want to select anonymous value then you can't cast it to string[] the best way is var like:

var NamesArray = Users.OrderByDescending(i => i.FirstName)
             .Select(i => new { i.FirstName , i.LastName})
             .Distinct()
             .ToArray();

but it is also give you a list of object with FirstName and LastName properties.

but another workaround would be like:

var NamesArray = Users.OrderByDescending(i => i.FirstName)
            .Select(i => new string[] { i.FirstName, i.LastName })
            .Distinct()
            .ToArray();
foreach(string[] str in NamesArray)
{
     string firstName = str[0];
     string lastName = str[1];
}

Or:

List<string[]> NamesArray = Users.OrderByDescending(i => i.FirstName)
        .Select(i => new string[] { i.FirstName, i.LastName })
        .Distinct().ToList();

Or:

IEnumerable<string[]> NamesArray = Users.OrderByDescending(i => i.FirstName)
            .Select(i => new string[] { i.FirstName, i.LastName })
            .Distinct();
foreach(string[] str in NamesArray)
{
    string firstName = str[0];
    string lastName = str[1];
}

anyway you can't cast it directly to string[] means NamesArray can't be string[].

Aria
  • 3,313
  • 1
  • 16
  • 46
  • Now it says: "Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignment, simple name or memeber acces"? –  Jan 13 '18 at 09:41
  • and what do you mean with sss? –  Jan 13 '18 at 09:43
  • @A.Vreeswijk, Yes it was wrong at the first go, I have edited, try it again. – Aria Jan 13 '18 at 09:43
  • I was looking to the code, but there is one problem with it. Your code is creating a string with 2 values, but I want 2 separate values (not in 1 string). –  Jan 13 '18 at 11:47
  • So you can't cast it to `string[]` array, I explained why. – Aria Jan 13 '18 at 12:09