【问题标题】:Implicit conversion error in LINQLINQ 中的隐式转换错误
【发布时间】:2013-04-12 12:29:32
【问题描述】:

我有所有 ID 的列表。

//代码

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

我正在使用上述 LINQ 查询,但出现编译错误:

//错误

无法隐式转换类型 System.Collections.Generic.List 到 System.Collections.Generic.List

我想根据字符“_”对成员字段AddressId 进行子串操作。

我哪里错了?

【问题讨论】:

  • 您正在尝试将List&lt;string&gt; 分配给List&lt;IAddress&gt;...

标签: c# .net linq


【解决方案1】:

你在 where 中找到你想要的地址,然后你从 id 中选择一些字符串。

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

Select(s =&gt; s.AddressId.Substring(s.AddressId.IndexOf("_"))).ToList();返回子字符串列表

只需将其删除并使用

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

作为

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

过滤 AllID 列表,但将它们保留为 IAddresss

如果你改写成这样你应该可以看出问题出在哪里

你说

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>

但你想要

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>

【讨论】:

    【解决方案2】:

    如果你想用 Linq 查询更新AddressId,你可以这样做:

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

    注意.ForEach()不是Linq扩展,而是List类的方法。

    由于 IndexOf 可能很耗时,请考虑缓存值:

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

    【讨论】:

      【解决方案3】:

      您的选择操作.Select(s =&gt; s.AddressId.Substring(s.AddressId.IndexOf("_"))) 不会修改您的对象,它将每个对象投影到一个子字符串。因此.ToList() 返回一个List&lt;string&gt;

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-03-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多