C# 3.0 in a Nutshell
C# 3.0 in a Nutshell, Third Edition A Desktop Quick Reference By Joseph Albahari, Ben Albahari
September 2007
Pages: 858


Welcome Guest ( Log In | Register )

 
Reply to this topicStart new topic
Oftype<>().summary For A General Datasource.
Thinkly
post Jun 2 2009, 02:49 AM
Post #1


New Member
*

Group: Members
Posts: 1
Joined: 2-June 09
Member No.: 18,429



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
Go to the top of the page
 
+Quote Post
JoeAlbahari
post 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

Go to the top of the page
 
+Quote Post

Reply to this topicStart new topic
1 User(s) are reading this topic (1 Guests and 0 Anonymous Users)
0 Members:

 

RSS Lo-Fi Version Time is now: 22nd November 2009 - 05:10 AM