Search code examples
c#linq

Converting a nested for-each to use LINQ and JOIN


I have some for-each loops I am trying to convert to use LINQ with probably a JOIN I started writing it myself but couldn't quite figure it out. I have posted my half attempt too.

and I started writing it like this but couldn't quite figure our how to proceed:


Solution

  • Using SelectMany you can achieve what you want with a little bit of weirdness like the below :

    var result = metaData.SelectMany(r=> myDictionary,(meta,dict)=>  dict.TryGetValue(meta.PropName,out var val) ? new { val,meta } : null)
    .Where(r=> r != null || !string.IsNullOrEmpty(r.val.ToString()))
    .Where(r=> r.val.GetType().IsArray ? 
           ((IEnumerable)r.val).Cast<object?>()
          .Select(v=> SomePrivateMethodCall(v, r.meta.PropertyType.GetElementType()))
                             .Any(result => !result) :
     !SomePrivateMethodCall(r.val, r.meta.PropertyType) )
    .Select(r=> r.meta.PropName)).ToArray()