简体   繁体   中英

Implicit conversion error in LINQ

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 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 IAddress s

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>

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_ ));

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM