Home C# Class select multiple fields in Xamarin
Reply: 1

C# Class select multiple fields in Xamarin

A. Vreeswijk
1#
A. Vreeswijk Published in 2018-01-13 09:33:28Z

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???

Aria
2#
Aria Reply to 2018-01-13 12:43:05Z

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[].

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.299266 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO