将对象列表转换为枚举词典作为键并将对象列表作为值转换时出现错误

时间:2018-01-15 21:58:39

标签: c# dictionary casting

我有枚举/类如下

    func request(_ command: Router, params: [String: AnyObject]?, completion: @escaping (Result<JSON>)-> Void){
        var parameters = ["nonce": Int(Date().timeIntervalSince1970*1000) as AnyObject]
        if params != nil{
            parameters = parameters + params!
        }
let sign = customerSecret.sha512
        print(sign)
        let headers:HTTPHeaders = ["key": APIKey, "sign": sign]
        do{
            try Alamofire.request( command.asURL(), method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers).responseJSON{(response) in
                guard let json = response.result.value else {
                    completion(.failure(CoinSpotError.networkError(error: response.result.error)))
                    return
                }
                print(response)
            }
        } catch {
            print("error")
        }
    }

其用法如下

public enum TestType
{
    Automatic,
    Manual,
    SemiManual,
    SemiAutomatic
}

public class TestCase
{
    public int Id { get; set; }

}

public class TestData
{
    public TestType TestType { get; set; }
    public int Id { get; set; }
}

我需要将此列表转换为static void Main(string[] args) { List<TestData> data = new List<TestData>() { new TestData(){ TestType = TestType.Automatic, Id = 21 }, new TestData(){ TestType = TestType.SemiAutomatic, Id = 34 }, new TestData(){ TestType = TestType.SemiManual, Id = 13 }, new TestData(){ TestType = TestType.Manual, Id = 14 }, new TestData(){ TestType = TestType.Automatic, Id = 45 }, new TestData(){ TestType = TestType.Automatic, Id = 56 } }; } 。为此,我的代码如下。

Dictionary<TestType, List<TestCase>>
  

错误CS0029无法隐式转换类型   &#39; Dictionary<TestType, List<TestCase>> dataAsDictionary = data.GroupBy(x => x.TestType) .ToDictionary(k => k.Key, v => v.Select( f=> new TestCase() { Id = f.Id })); &#39;至   &#39; System.Collections.Generic.Dictionary<ConsoleApp2.TestType, System.Collections.Generic.IEnumerable<ConsoleApp2.TestCase>>&#39; ConsoleApp2

如何解决此错误?我尝试了各种铸造组合,但这似乎没有帮助

2 个答案:

答案 0 :(得分:2)

添加Select来电:

IEnumerable<T>

这是必要的,因为List<T>返回parent_recipe_id而不是parent_recipe

答案 1 :(得分:2)

您收到此错误是因为Select()返回IEnumerable<T>,而您的Dictionary想要List<T>类型的值。

添加ToList()来调解此问题:

Dictionary<TestType,List<TestCase>> dataAsDictionary = data
    .GroupBy(x => x.TestType)
    .ToDictionary(
        k => k.Key
    ,   v => v.Select( f=> new TestCase() { Id = f.Id }).ToList()
    ); //                                               ^^^^^^^^^