简体   繁体   中英

How do I easily Collection information from the Visual Studio immediate window

Sometimes execute a ToList() on a collection and it doesn't return much useful information. How can I get useful information from collections and child collections?

While it would be nice to be able to use LINQ in the immediate window I haven't seen a reliable solution as of yet. It sure would be nice. However, if you need some information quickly you can use the following extension methods. Unfortunately this won't filter your lists.

  public static class EnumerableExtensions
{
    public static List<String> PropertyNames(this IEnumerable list)
    {
        var items = list.OfType<Object>();
        return items.Any()
            ? items.First().GetType()
                .GetProperties(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public)
                .Select(p => p.Name).ToList()
            : new List<string>();
    }

    public static List<Object> Peek(this IEnumerable list, String name)
    {
        var data = from object item in list let property = item.GetType()
                   .GetProperty(name, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public) 
               where property != null select property.GetValue(item, null);
        return data.OfType<Object>().ToList();
    }
}

You can then start getting info as follows in the immediate window: (Don't forget extension method references)

myList.Peek("CustomObject"); // Get a list of CustomObject child property.

And if you need the properties.

myList.Properties() // Get a list of property names.

And you can chain them fine.

myList.Peek("CustomObject").PropertyNames(); // Get names => Found "Height" property.
myList.Peek("CustomObject").Peek("Height");  // Get a list of heights. 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM