【问题标题】:Convert generic.list<string> to generic list product将 generic.list<string> 转换为通用列表产品
【发布时间】:2013-06-04 09:55:19
【问题描述】:

我有这样的代码:

  var list = _appData.GetAdvanceSearchData(Convert.ToInt16(collection["Product"])).ToList();
   List<ProductMaterial> materials = list.Select(x => x.ProductMaterial).Distinct().ToList();

我得到了例外:

Cannot implicitly convert type 'System.Collections.Generic.List<string>' to 'System.Collections.Generic.List<Crescent.LinqModel.ProductMaterial>' 

应该做什么?

产品材质类:

 public class ProductMaterial
{
    public string ProductMaterials {get;set;}
}

list.Select(x => x.ProductMaterial).Distinct().ToList() 给了我数组字符串虽然已转换为列表,但我想要'ProductMaterial'类型的结果。

【问题讨论】:

  • ProductMaterial 的类型是什么?字符串还是自定义类?

标签: linq entity-framework


【解决方案1】:

改用这个:

var materials = list.Select(x => x.ProductMaterial).Distinct().ToList();

或者:

List<string> materials = list.Select(x => x.ProductMaterial).Distinct().ToList();

唯一不同的是materials变量的类型。

【讨论】:

    【解决方案2】:

    我猜你想要DistinctBy

    List<ProductMaterial> materials =
        list.DistinctBy(x => x.ProductMaterial).ToList();
    

    你可以使用那个扩展方法或者搜索一些other implementation here

    【讨论】:

      【解决方案3】:

      查询list.Select(x =&gt; x.ProductMaterial).Distinct().ToList(); 返回List&lt;string&gt; 而不是List&lt;ProductMaterial&gt;

      您可以使用 List 代替 List&lt;ProductMaterial&gt;。 我不确定你想要什么。如果指定了列表的数据类型,我可以给出更准确的意见。

      【讨论】:

      • @DharaPPatel var list 的数据类型是什么?如果 var list 是 List 那么您可以使用 WHERE 而不是 SELECT 来查询不同的条目
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多