我有一个方法是返回一个列表的List<KeyValuePair<int,string>>
;然而,我发现了一个错误:无法将源类型转换为目标类型List <KeyValuePair> Linq
Cannot convert source type
System.Collections.Generic.List<{Key:int, Value:string}>
to target typeSystem.Collections.Generic.KeyValuePair<'int,string'>>
.
我试图做一个LINQ的select语句到一个新的列表,但我不明白,如果初始化列表是问题,或者它如何我越来越Linq语句中的值。
这里是方法:
public static List<KeyValuePair<int,string>> GetStatus(int status)
{
List<KeyValuePair<int,string>> st = SelectList.GetStatuses();
List<KeyValuePair<int,string>> tp;
switch(status)
{
case (int)Status.Completed:
tp = st.Where(s => s.Key == (int)Status.Completed ||
s.Key == (int)Status.NotValid)
.Select(s => new { s.Key, s.Value }).ToList();
case (int)Status.Open:
tp = st.Where(s => s.Key == (int)Status.Open ||
s.Key == (int)Status.Reviewed)
.Select(s => new { s.Key, s.Value }).ToList();
default:
break;
}
return tp;
}
下面是填充列表的方法:
public static List<KeyValuePair<int, string>> GetStatuses()
{
using (var con = new SqlConnection())
{
var sql = @"SELECT ID [Key], Text [Value] from Statuses";
return (con.Query<KeyValuePair<int, string>>(sql.ToString(), commandType: commandType:Text) ?? Enumerable.Empty<KeyValuePair<int, string>>()).ToList();
}
}
他的返回类型是一个列表,所以ToList是必要的btw –
@JustinPihony谢谢,编辑。 –
我不知道我可以完全删除选择部分,但这当然确实使它有效且易于阅读。谢谢Ben,Sergey,Justin! –