c# - Collection to Count Converter -
how convert collection count?
where when collection passed converter should able return count following collections,
dictionary
, observablecollection
or list
right have following doesn't work,
public object convert(object value, type targettype, object parameter, cultureinfo culture) { return ((system.collections.icollection)value) != null ? ((system.collections.icollection)value).count : 0; }
if define "collection" implements icollection
or icollection<t>
count property available tell number of elements in collection if need know.
if wish calculate value based upon icollection.count modified in way can create generic method calculate value us. example, generic method convert<t>
take icollection<t> value
formal parameter. such function invoked using implements icollection<t>
actual parameter.
because compiler can infer generic type argument don't need explicitly specify type argument when invoking generic method (although can if want or need to).
for example...
class program { static public int convert<t>(icollection<t> value, type targettype, object parameter, cultureinfo culture) { return value.count; } static void main(string[] args) { dictionary<int, string> di = new dictionary<int,string>(); di.add(1, "one"); di.add(2, "two"); di.add(3, "three"); console.writeline("dictionary count: {0}", di.count); console.writeline("dictionary convert: {0}", convert(di, null, null, null)); observablecollection<double> oc = new observablecollection<double>(); oc.add(1.0); oc.add(2.0); oc.add(3.0); oc.add(4.0); console.writeline("observablecollection count: {0}", oc.count); console.writeline("observablecollection convert: {0}", convert(oc, null, null, null)); list<string> li = new list<string>(); li.add("one"); li.add("two"); li.add("three"); li.add("four"); li.add("five"); console.writeline("list count: {0}", li.count); console.writeline("list convert: {0}", convert(li, null, null, null)); console.readline(); } }
Comments
Post a Comment