2

I have a list AllIDs:

List<IAddress> AllIDs = new List<IAddress>();

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

I am using below LINQ query but getting compilation error:

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

Error:

Cannot implicitly convert type 'System.Collections.Generic.List<string>' to 'System.Collections.Generic.List<MyCompany.Common.Users.IAddress>'

3 답변


3

AllIDs is a list of IAddress but you are selecting a string. The compiler is complaining it cannot convert a List<string> to a List<IAddress>. Did you mean the following instead?

var substrings = AllIDs.Where(...).Select(...).ToList();


  • But Problem is I want to provide the resultant list as a datasource for a dropdown. And the resultant List does not have the property AddressID. - user1740172

0

If you want to put them back into Address objects (assuming you have an Address class in addition to your IAddress interface), you can do something like this (assuming the constructor for Address is in place):

AllIDs = AllIDs.Where(...).Select(new Address(s.AddressID.Substring(s.AddressID.IndexOf("_")))).ToList();

You should also look at using query syntax for LINQ instead of method syntax, it can clean up and improve the readability of a lot of queries like this. Your original (unmodified) query is roughly equivalent to this:

var substrings = from a in AllIDs
                 let id = a.AddressId
                 let idx = id.IndexOf("_")
                 where id.Length >= idx
                 select id.Substring(idx);

Though this is really just a style thing, and this compiles to the same thing as the original. One slight difference is that you only have to call String.IndexOf() one per entry, instead of twice per entry. let is your friend.


  • Hi Matthew thanks for the response. But Problem is I want to provide the resultant list in your example substrings as a datasource for a dropdown. And the resultant List will not have the property AddressID which is being used as below. ddl.DataSource = AllIDs; ddl.DataTextField = "AddressID"; ddl.DataValueField = "AddressID"; ddl.DataBind(); I can use ForEach but want to do it using LINQ. Any pointers?? - user1740172
  • Look at wasp's solution, it should work with this databinding. - Matthew Kennedy

0

Maybe this?

var boundable  = 
    from s id in AllIDs
    where s.AddressId.Length >= s.AddressId.IndexOf("_")
    select new { AddressId = s.AddressId.Substring(s.AddressId.IndexOf("_")) };
boundable = boundable.ToList();

Related

Latest