linq 如何运行基于字典的委托(C#)

lkaoscv7  于 2023-03-10  发布在  C#
关注(0)|答案(2)|浏览(147)

我有模拟类与以下:

private readonly List<SomeObject> m_objectsList = new List<SomeObject>();

public Task<IList<Auto>> Todo(SomeParams params)
{
 IEnumerable<Auto> matches = m_objectsList.Select(GetMyObject);
 return Task.FromResult<IList<Auto>>(matches.ToArray());
}

private Auto GetMyObject(SomeObject s)
{
 Auto newAuto = new Auto
 {
     Id = s.Id,
     Name = s.Name,
 };    
 return newAuto;
}

这是正常的。现在我想这样做:

private readonly Dictionary<SomeObject, SomeParams> m_objectsList2 = 
                                                 new Dictionary<SomeObject, SomeParams>();

public Task<IList<Auto>> Todo2(SomeParams params)
{
 IEnumerable<Auto> matches = m_objectsList2.Select(GetMyObject2);
 return Task.FromResult<IList<Auto>>(matches.ToArray());
}

private Auto GetMyObject2(SomeObject s, SomeParams p)
 {
  Auto newAuto = new Auto();
     ....//some code
     return newAuto;
 }

但出现编译器错误CS0411。

7ivaypg9

7ivaypg91#

Dictionary<TKey, TValue>实现了IEnumerable<KeyValuePair<TKey, TValue>>,但由于类型不匹配,编译器无法执行method group到委托的转换。请从使用方法组切换到使用lambda:

IEnumerable<Auto> matches = m_objectsList2.Select(kvp => GetMyObject2(kvp.Key, kvp.Value));

或更改方法的签名(或添加重载):

private Auto GetMyObject2(KeyValuePair<SomeObject, SomeParams> kvp)
{
     var (s, p) = kvp; // use deconstruction
     // or for older compilers/framework versions
     // var s = kvp.Key;
     // var p = kvp.Value;
     Auto newAuto = new Auto();
     ....//some code
     return newAuto;
}
58wvjzkj

58wvjzkj2#

可以尝试修改您的Todo2

public Task<IList<Auto>> Todo2()
{
   // Removed params parameter as I don't see the usage. Please add back if you need it
    return Task.FromResult<IList<Auto>>(m_objectsList2.Select(p => GetMyObject2(p.Key, p.Value)).ToArray());
}

相关问题