String 这个LINQ查询中出现了什么错误,编译错误

String 这个LINQ查询中出现了什么错误,编译错误,string,linq,list,String,Linq,List,我有一个列表所有ID: List<IAddress> AllIDs = new List<IAddress>(); 错误: 无法将类型“System.Collections.Generic.List”隐式转换为“System.Collections.Generic.List” AllIDs是IAddress的列表,但您正在选择一个字符串。编译器抱怨无法将列表转换为列表。你的意思是说以下内容吗 var substrings = AllIDs.Where(...).Sele

我有一个列表
所有ID

List<IAddress> AllIDs = new List<IAddress>();
错误:

无法将类型“System.Collections.Generic.List”隐式转换为“System.Collections.Generic.List”


AllIDs
IAddress
的列表,但您正在选择一个
字符串。编译器抱怨无法将
列表
转换为
列表
。你的意思是说以下内容吗

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

如果要将它们放回
Address
对象中(假设除了
IAddress
接口之外还有一个
Address
类),可以执行类似操作(假设
Address
的构造函数已就位):

您还应该考虑使用LINQ的查询语法而不是方法语法,它可以清理和提高许多类似这样的查询的可读性。原始(未修改)查询大致相当于:

var substrings = from a in AllIDs
                 let id = a.AddressId
                 let idx = id.IndexOf("_")
                 where id.Length >= idx
                 select id.Substring(idx);
虽然这实际上只是一个风格的东西,这编译成与原始相同的东西。一个细微的区别是,每个条目只需调用
String.IndexOf()
一个,而不是每个条目调用两次<代码>让
是你的朋友。

也许是这个

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

但问题是我想提供结果列表作为下拉列表的数据源。结果列表没有属性AddressID。您好,Matthew,谢谢您的回复。但问题是我想在您的示例子字符串中提供结果列表作为下拉列表的数据源。结果列表将不具有如下使用的属性AddressID。ddl.DataSource=AllIDs;ddl.DataTextField=“AddressID”;ddl.DataValueField=“AddressID”;ddl.DataBind();我可以使用ForEach,但想使用LINQ。任何指示??看看wasp的解决方案,它应该与这个数据绑定一起工作。
var substrings = from a in AllIDs
                 let id = a.AddressId
                 let idx = id.IndexOf("_")
                 where id.Length >= idx
                 select id.Substring(idx);
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();