2

I have list of all ID's.

//Code

List<IAddress> AllIDs = new List<IAddress>();
AllIDs= AllIDs.Where(s => s.AddressId.Length >= s.AddressId.IndexOf("_"))
              .Select(s => s.AddressId.Substring(s.AddressId.IndexOf("_")))
              .ToList();

I am using the above LINQ query but getting compilation error:

//Error

Cannot implicitly convert type System.Collections.Generic.List to System.Collections.Generic.List

I want to to substring operation on a member field AddressId based on a character "_".

Where am I wrong?


  • You're trying to assign a List<string> to List<IAddress>... - Patryk Ćwiek

3 답변


3

You find the addresses you want with the where but then you select some strings from the id.

s.AddressId.Substring(s.AddressId.IndexOf("_")) is string

ie Select(s => s.AddressId.Substring(s.AddressId.IndexOf("_"))).ToList(); returns a list of substrings

Just remove it and use

AllIDs= AllIDs.Where(s => s.AddressId.Length >= s.AddressId.IndexOf("_")).ToList()

as

Where(s => s.AddressId.Length >= s.AddressId.IndexOf("_")) 

filters the list of AllIDs but keeps them as IAddresss

if you rewrite is like this you should be able to see what the problem is

you said

var items  = from addr in AllIds 
             where addr.AddressId.Length >= addr.AddressId.IndexOf("_") // filter applied
             select addr.AddressId.Substring(s.AddressId.IndexOf("_")); // select a string from the address

AllIDs = items.ToList(); // hence the error List<string> can't be assigned to List<IAddress>

but you wanted

var items  = from addr in AllIds 
             where addr.AddressId.Length >= addr.AddressId.IndexOf("_") // filter applied
             select addr;                        // select the address

AllIDs = items.ToList(); // items contains IAddress's so this returns a List<IAddress>


1

If you want to update AddressId with a Linq query, you can do it this way:

AllIDs.Where(s => s.AddressId.Length >= s.AddressId.IndexOf("_"))
      .ToList()
      .ForEach(s => s.AddressId = s.AddressId.Substring(s.AddressId.IndexOf("_")));

Note that .ForEach() is not a Linq extension, but a method of the class List< T >.

Since IndexOf could be time consuming, think about caching the value:

AllIDs.Select(s => new { Address = s, IndexOf_ = s.AddressId.IndexOf("_") })
      .Where(s => s.Address.AddressId.Length >= s.IndexOf_ )
      .ToList()
      .ForEach(s => s.Address.AddressId = s.Address.AddressId.Substring(s.IndexOf_ ));


0

Your select operation .Select(s => s.AddressId.Substring(s.AddressId.IndexOf("_"))) does not modify your objects, it projects each object to a substring. Thus .ToList() returns a List<string>.

Related

Latest