从List <value>转换为IEqualityComparer <string>

时间:2015-07-28 18:16:31

标签: c# linq

我有Dictionary<string, List<Value>> FormControllerNamesValues财产 在我的POCO对象中,此字典将包含下拉控制器名称的所有下拉控制器名称和选项列表。我的问题我不能有这个编译错误

  

错误4参数3:无法转换   'System.Collections.Generic.List&LT; Model.Value&GT;'至   'System.Collections.Generic.IEqualityComparer&LT;串GT;'

我想问一下如何修复此错误

List<Value> dropDownListrValue =
    (from val in db.Values
     where val.ParentId == (from va in db.Values
                            where va.ParentId == (from value3 in db.Values
                                                  where value3.Name == formType
                                                  select value3.RecordId).FirstOrDefault()
                            select va.RecordId).FirstOrDefault()
    select val).ToList();
result = (from value1 in db.Values
          where value1.Name == formType
          select
              new ItemManagement
              {
                  FormType = value1.Name,
                  RecordID = value1.RecordId,     
                  FormControllerNames = 
                      (from va in db.Values 
                       where va.ParentId == (from value3 in db.Values where value3.Name ==formType select value3.RecordId).FirstOrDefault()
                       select va).ToDictionary(va => va.Name, dropDownListrValue)
              }).ToList();

这是我的ItemManagement课程:

public class ItemManagement
{
    public long RecordID { get; set; }
    public String FormType { get; set; }
    public Dictionary<string, List<Value>> FormControllerNamesValues { get; set; }

}

1 个答案:

答案 0 :(得分:2)

错误是由包含无效参数的.ToDictionary(va => va.Name, dropDownListrValue)方法调用引起的。编译器将此调用解析为

public static Dictionary<TKey, TSource> ToDictionary<TSource, TKey>(
    this IEnumerable<TSource> source,
    Func<TSource, TKey> keySelector,
    IEqualityComparer<TKey> comparer
)

overload,由于dropDownListrValue没有实现IEqualityComparer接口,因此会抛出编译错误。

您可以将呼叫更改为.ToDictionary(va => va.Name, va => dropDownListrValue)以修复编译错误。此方法调用将解析为

public static Dictionary<TKey, TElement> ToDictionary<TSource, TKey, TElement>(
    this IEnumerable<TSource> source,
    Func<TSource, TKey> keySelector,
    Func<TSource, TElement> elementSelector
)

overload,并返回一个字典,其中包含每个dropDownListrValue键的va.Name值,假设这是您想要实现的目标。