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