1

I have Mock class with below:

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;
}

This is working OK. Now I want to do like:

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;
 }

but getting Compiler Error CS0411.

4est
  • 3,010
  • 6
  • 41
  • 63
  • I don't see how your code can work. You have too many type errors. Why is the name `m_objectsList2` when it is `Dictionary<>`? Why do you think `GetMyObject2` matches the signature of the `Func<>` required as a paramter for `Select`? What are the types you haven't defined? – NetMage Mar 01 '23 at 18:45
  • `Dictionary` is the wrong structure for this kind of thing. – Enigmativity Mar 02 '23 at 06:01

2 Answers2

1

Dictionary<TKey, TValue> implements IEnumerable<KeyValuePair<TKey, TValue>>, and compiler can't perform method group conversion to delegate due to type mismatch. Either switch from using method group to lambda:

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

Or change signature of the method (or add an overload):

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;
}
Guru Stron
  • 102,774
  • 10
  • 95
  • 132
0

Can try modifying your 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());
}
sam
  • 1,937
  • 1
  • 8
  • 14