Oftype<>().summary For A General Datasource. |
![]() ![]() |
Oftype<>().summary For A General Datasource. |
Jun 2 2009, 02:49 AM
Post
#1
|
|
|
|
I am working on a query tools, which is based on dynamic Linq.
I have the following code in LinqPad: ************************************* List<object> list=new List<object>(); list.Add(Categories.First()); list.Add(Products.Take (10)); list.Select(p=>new {name=p.GetType().Name,countOfProducts=(p as IEnumerable<Products>).Count()}).Dump(); ************************************* It will throw an exception : ************************************* Value cannot be null. Parameter name: source Message Value cannot be null. Parameter name: source ParamName source Data InnerException null TargetSite 6RuntimeMethodInfo Enumerable.Count (IEnumerable<TSource> source) Name Count ... ************************************* Of course, If I don't add the category to the list in the code, all works fine. Why do I try this? It is because I want to have a data favorites, so that I can add all kinds of object in the list. But I want to know the object's count of its children if it is an IEnumerable<>. Or I hope it will return null, 0 at least. I was blocked here. Thank you in advance for all kinds of suggestions. Ying |
|
|
|
Jun 2 2009, 05:19 AM
Post
#2
|
|
|
Advanced Member ![]() ![]() ![]() ![]() ![]() ![]() Group: Members Posts: 215 Joined: 15-February 08 From: Perth, Australia Member No.: 90 |
You could write a custom method to help here:
CODE static int? CountIfEnumerable (object o) { var numerable = o as IEnumerable; if (numerable == null) return null; int count = 0; foreach (var item in numerable) count++; return count; } Joe |
|
|
|
![]() ![]() |
|
Lo-Fi Version | Time is now: 22nd November 2009 - 05:10 AM |