Where does this Linq statement get the selected value?

I tried using the following Linq statement:

private static void Test(object instance)
{
    PropertyInfo[] propertyInfos = instance.GetType().GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance)    
    var pis = from pi in
                  (from propertyInfo
                      in propertyInfos
                  select new {
                      PropertyInfo = propertyInfo,
                      Attribute = propertyInfo.GetCustomAttribute(typeof(Attribute))
                  })
              where pi.Attribute != null
              select pi;
    // End of test method
}

      

I thought there must be an easier way to do this. However, the reflector tells me that this statement makes it easy:

private static void Test(object instance)
{
    var pis = from propertyInfo in instance.GetType().GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance)
        let Attribute = propertyInfo.GetCustomAttribute(typeof(Attribute))
        where Attribute != null
        select pi;
   // End of reflector output
}

      

and now I'm wondering where pi

...

Edit

If I add the following lines to my source code:

foreach (var item in pis)
    Debug.WriteLine(item.Attribute.ToString() + " " + item.PropertyInfo.Name);

      

they appear unchanged in the reflected code. It looks like it pi

really refers to the type new { PropertyInfo, Attribute }

even though the instance is never instantiated. Therefore, the choice is propertyInfo

not possible.

+3


source to share


1 answer


Any reflector you use will get an error. should be . But it is correct to say that your query can be simplified in this way. pi

propertyInfo

Your request can be simplified as follows:



var pis = from propertyInfo in instance.GetType().GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance)
    let attribute = propertyInfo.GetCustomAttribute(typeof(Attribute))
    where attribute != null
    select new {propertyInfo, attribute};

      

+3


source







All Articles