Home > Net >  .ToString().ToList() returns a New List<char>
.ToString().ToList() returns a New List<char>

Time:01-10

So I have a Query that searches for various items. But I just want their Id so I used a projection to return me only the Ids and not the other elements of the item. but converting from ObjectId .ToString() and then .ToList() returns me a List<char> instead List<string>

var items = await this.ItemAppService.GetAllAsync(expression,
               x => new
               {
                  Ids = x.Id.ToString().ToList(),
               });
           var Ids = items.SelectMany(x => x.Ids.Select(x => x)).ToList();

I would like to understand why i'm returning a List<Char> and how I convert it to List<String>

CodePudding user response:

.ToString().ToList() returns a New List<char>

Yes, because a string is an IEnumerable<char> (a bunch of characters that can be enumerated over). ToList is an extension method on all IEnumerable<T>, that returns a List<T>.

So the Ids property in the anonymous object is already a List<char>:

x => new
{
   // this "Ids" is already a List<char>
   Ids = x.Id.ToString().ToList(),
});

You then do some more shuffling on it, but not meaningfully changing anything. x.Ids.Select(x => x) returns an Innumerable<char> with the same contents as x.Ids. And SelectMany adds up all those IEnumerable<char> in each of the anonymous objects into one big IEnumerable<char>, which you then convert to a list.

I'm not sure why you have used an anonymous object here. If you just want a List<string> with all the IDs, just do:

var ids = await this.ItemAppService.GetAllAsync(
              expression,
              // assuming x.Id is not already a string
              x => x.Id.ToString()
          ).ToList();

CodePudding user response:

The first ToList is unnecessary, you want strings, and with that ToList() invocation you are converting your strings to char arrays. So the code should be rewritten as:

var items = await this.ItemAppService.GetAllAsync(expression,
    x => new
    {
        Id = x.Id.ToString(),
    });
var ids = items.Select(x => x.Id).ToList();
  • Related