473,320 Members | 1,969 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

Is it possible to access properties of Generic types?

I have a Class "Multidictionary" which I created which is basically a
dictionary which can have multiple values for the same key. The class centers
around
private Dictionary<K, List<V>_InnerDictionary;
and provides methods to add to the InnerDictionary, remove from the
InnerDictionary and so forth.
I would like to have methods which allow me to retrieve or renmove single
value items based on a specific value of one pf their properties. I can't
figure out how to be able to examine the values of properties of a geneic
type. I suspect that it is possible with Reflection, but I can't find.
What I am thinking of is something like:

public void RemoveItemsWithSpecificValuePropertyValue(P
comparisonValue)
{
foreach (K key in _InnerDictionary)
{
foreach (V value in K)
{
if (value.P == comparisonValue)//This is the part that I
don't know how to do
{
// Remove value from list
}
}
}
}

Thanks for any help!
Ethan

Jun 27 '08 #1
7 3975
On Jun 13, 11:28*am, Ethan Strauss
<EthanStra...@discussions.microsoft.comwrote:
I have a Class "Multidictionary" which I created which is basically a
dictionary which can have multiple values for the same key. The class centers
around
* * * * private Dictionary<K, List<V>_InnerDictionary;
Yep, that is how it;s done

one qeustion though, where is your class defined ???
In the code above you are simply using the Dictionary class provided
by the framework

Of course you can do it with reflection, the fact that It's "generic"
has nothing to do., if you have something like

note that this code was written in the google's editor, not tested or
compiled

class MyDir<TKey, TValue>: Dictionary<Tkey, TValue>{

public object FindByProperty( TKey key, string pName ){
//decide if TValue is enumerable or no
if ( this[TKey] is IEnumerable )
{
foreach(object o in (IEnumerable) this[TKey] )
if ( HasValue( o, pName ) )
return o;
}
else
return HasValue ( this[TKey], pName ) ? this[TKey]: null;
}

HasValue( object o, string propertyName )
{
// use reflection to get the value
}

}
and provides methods to add to the InnerDictionary, remove from the
InnerDictionary and so forth.
* * * * I would like to have methods which allow me to retrieve orrenmove single
value items based on a specific value of one pf their properties. I can't
figure out how to be able to examine the values of properties of a geneic
type. I suspect that it is possible with Reflection, but I can't find.

What I am thinking of is something like:

* * * * public void RemoveItemsWithSpecificValuePropertyValue(P
comparisonValue)
* * * * {
* * * * * * foreach (K key in _InnerDictionary)
* * * * * * {
* * * * * * * * foreach (V value in K)
* * * * * * * * {
* * * * * * * * * * if (value.P == comparisonValue)//This is the part that I
don't know how to do
* * * * * * * * * * {
* * * * * * * * * * * * // * * *Remove valuefrom list
* * * * * * * * * * }
* * * * * * * * }
* * * * * * }
* * * * }

Thanks for any help!
Ethan
Jun 27 '08 #2
Thanks!
Can you expand on your "HasValue" method? I have never used reflection I
can't figure that bit out. I think I can handle the rest once I get that.
Ethan

"Ignacio Machin ( .NET/ C# MVP )" wrote:
On Jun 13, 11:28 am, Ethan Strauss
<EthanStra...@discussions.microsoft.comwrote:
I have a Class "Multidictionary" which I created which is basically a
dictionary which can have multiple values for the same key. The class centers
around
private Dictionary<K, List<V>_InnerDictionary;

Yep, that is how it;s done

one qeustion though, where is your class defined ???
In the code above you are simply using the Dictionary class provided
by the framework
I didn't show most of the code for the class. The rest is constructors and
methods to interact with that dictionary.
>
Of course you can do it with reflection, the fact that It's "generic"
has nothing to do., if you have something like

note that this code was written in the google's editor, not tested or
compiled

class MyDir<TKey, TValue>: Dictionary<Tkey, TValue>{

public object FindByProperty( TKey key, string pName ){
//decide if TValue is enumerable or no
if ( this[TKey] is IEnumerable )
{
foreach(object o in (IEnumerable) this[TKey] )
if ( HasValue( o, pName ) )
return o;
}
else
return HasValue ( this[TKey], pName ) ? this[TKey]: null;
}

HasValue( object o, string propertyName )
{
// use reflection to get the value
}

}
and provides methods to add to the InnerDictionary, remove from the
InnerDictionary and so forth.
I would like to have methods which allow me to retrieve or renmove single
value items based on a specific value of one pf their properties. I can't
figure out how to be able to examine the values of properties of a geneic
type. I suspect that it is possible with Reflection, but I can't find.

What I am thinking of is something like:

public void RemoveItemsWithSpecificValuePropertyValue(P
comparisonValue)
{
foreach (K key in _InnerDictionary)
{
foreach (V value in K)
{
if (value.P == comparisonValue)//This is the part that I
don't know how to do
{
// Remove value from list
}
}
}
}

Thanks for any help!
Ethan

Jun 27 '08 #3
>foreach (K key in _InnerDictionary) {
foreach (V value in K) {
if (value.P == comparisonValue) {
// This is the part that I don't know how to do
// Remove value from list
}
}
}
I don't think you can do this. What you would want is to call the
"value.Remove()" method, but this would cause problems in your itteration.

Instead, look into something like this *untested* code:

for (int i = 0; i < _InnerDictionary.Count; i++) {
for (int j = 0; j < K.Count; j++) {
if (K[j].P == comparisonValue) {
K[j].Remove();
// or
_InnerDictionary.Item[i].Remove();
}
}
}
Jun 27 '08 #4
On Jun 13, 11:28 am, Ethan Strauss
<EthanStra...@discussions.microsoft.comwrote:
I have a Class "Multidictionary" which I created which is basically a
dictionary which can have multiple values for the same key. The class centers
around
private Dictionary<K, List<V>_InnerDictionary;
and provides methods to add to the InnerDictionary, remove from the
InnerDictionary and so forth.
I would like to have methods which allow me to retrieve or renmove single
value items based on a specific value of one pf their properties. I can't
figure out how to be able to examine the values of properties of a geneic
type. I suspect that it is possible with Reflection, but I can't find.

What I am thinking of is something like:

public void RemoveItemsWithSpecificValuePropertyValue(P
comparisonValue)
{
foreach (K key in _InnerDictionary)
{
foreach (V value in K)
{
if (value.P == comparisonValue)//This is the part that I
don't know how to do
{
// Remove value from list
}
}
}
}

Thanks for any help!
Ethan
What i think you are looking for is a constraint.
where V : (Some class which is a base class for your Vs or an
interface implemnted by V which has the property P)
Jun 27 '08 #5
You might be better-off with a "predicate" approach... this would let
the caller decide what are useful conditions to remove items, and
ensures type-safety while removing the need for reflection - for
example see below.

[example uses C# 3; if you don't have VS2008 let me know - the
approach is fine for C# 2 and .NET 2.0]

Marc

using System;
using System.Collections.Generic;
class Foo
{
public string Bar { get; set; }
public int Whatever { get; set; }
}
static class Program
{
static void Main()
{
var dict = new MultiDictionary<string, Foo>();
dict.Add("abc", new Foo { Bar = "item 1", Whatever = 4 });
dict.Add("def", new Foo { Bar = "item 2", Whatever = 4 });
dict.Add("abc", new Foo { Bar = "item 3", Whatever = 3 });
dict.Add("abc", new Foo { Bar = "item 4", Whatever = 9 });
dict.Add("ghi", new Foo { Bar = "item 5", Whatever = 4 });
int removed = dict.RemoveAll(foo =foo.Whatever == 4);
}
}
class MultiDictionary<TKey, TValue>
{
public void Add(TKey key, TValue value)
{
List<TValueitems;
if (!list.TryGetValue(key, out items))
{
items = new List<TValue>();
list.Add(key, items);
}
items.Add(value);
}
public int RemoveAll(Predicate<TValuematch)
{
List<TKeykillKeys = new List<TKey>();
int count = 0;
// remove all matching items, noting any sub-lists
// that are now empty
foreach (var pair in list)
{
count += pair.Value.RemoveAll(match);
if (pair.Value.Count == 0) killKeys.Add(pair.Key);
}
// remove the empty sub-lists
foreach (TKey killKey in killKeys)
{
list.Remove(killKey);
}
return count;
}
private Dictionary<TKey, List<TValue>list;

public MultiDictionary() : this(null) { }
public MultiDictionary(IEqualityComparer<TKeycomparer)
{
list = new Dictionary<TKey, List<TValue>>(
comparer ?? EqualityComparer<TKey>.Default);
}
}
Jun 27 '08 #6
Thanks Marc,
This approach looks very promising. I am using VS2005 (.Net 2.0), but I
think you have given enough direction to get me where I want to go.
Ethan

"Marc Gravell" wrote:
You might be better-off with a "predicate" approach... this would let
the caller decide what are useful conditions to remove items, and
ensures type-safety while removing the need for reflection - for
example see below.

[example uses C# 3; if you don't have VS2008 let me know - the
approach is fine for C# 2 and .NET 2.0]

Marc

using System;
using System.Collections.Generic;
class Foo
{
public string Bar { get; set; }
public int Whatever { get; set; }
}
static class Program
{
static void Main()
{
var dict = new MultiDictionary<string, Foo>();
dict.Add("abc", new Foo { Bar = "item 1", Whatever = 4 });
dict.Add("def", new Foo { Bar = "item 2", Whatever = 4 });
dict.Add("abc", new Foo { Bar = "item 3", Whatever = 3 });
dict.Add("abc", new Foo { Bar = "item 4", Whatever = 9 });
dict.Add("ghi", new Foo { Bar = "item 5", Whatever = 4 });
int removed = dict.RemoveAll(foo =foo.Whatever == 4);
}
}
class MultiDictionary<TKey, TValue>
{
public void Add(TKey key, TValue value)
{
List<TValueitems;
if (!list.TryGetValue(key, out items))
{
items = new List<TValue>();
list.Add(key, items);
}
items.Add(value);
}
public int RemoveAll(Predicate<TValuematch)
{
List<TKeykillKeys = new List<TKey>();
int count = 0;
// remove all matching items, noting any sub-lists
// that are now empty
foreach (var pair in list)
{
count += pair.Value.RemoveAll(match);
if (pair.Value.Count == 0) killKeys.Add(pair.Key);
}
// remove the empty sub-lists
foreach (TKey killKey in killKeys)
{
list.Remove(killKey);
}
return count;
}
private Dictionary<TKey, List<TValue>list;

public MultiDictionary() : this(null) { }
public MultiDictionary(IEqualityComparer<TKeycomparer)
{
list = new Dictionary<TKey, List<TValue>>(
comparer ?? EqualityComparer<TKey>.Default);
}
}
Jun 27 '08 #7
I should add that there is an "EditableLookup<TKey,TValue>" that I
wrote, in Jon Skeet's "MiscUtil" and acts in a similar manner.
http://www.pobox.com/~skeet/csharp/miscutil

This maps to the .NET 3.5 ILookup<TKey,TValueinterface (and the
immutable Lookup<TKey,TValueclass), but IIRC it also compiles
in .NET 2.0 [we tried to get as much as possible to play nicely
with .NET 2.0]; I don't think it has a RemoveAll(predicate) method at
the moment, but it might make a useful starting point.

Marc
Jun 27 '08 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
by: Justin Shen | last post by:
you can define two class with same name but having different generic parameters in one assembly. As below: class Gen<T> { } class Gen<T1,T2> { }
17
by: Andreas Huber | last post by:
What follows is a discussion of my experience with .NET generics & the ..NET framework (as implemented in the Visual Studio 2005 Beta 1), which leads to questions as to why certain things are the...
3
by: Stephen Ahn | last post by:
Suppose I have object O with an event E that are defined in an assembly M that I am referencing in my code via reflection. M also defines object A which is an argument to E. At compile-time,...
4
by: Andrew Ducker | last post by:
I have a collection of classes descending from a single root class (let's call it RootClass). They all currently have a property of Logical, of type Logical. However they actually return a...
33
by: larpup | last post by:
I checked all my references prior to compiling. The mdb or mde works perfectly with full version of A2003. When running on a computer with RunTime i receive an error that a reference is broken...
4
by: =?Utf-8?B?c2lwcHl1Y29ubg==?= | last post by:
Hi I have a user control that is designed as below. I am creating these User Controls Dynamically in another form. They are multiple types of User Controls all with a common Interface so I can...
0
by: =?Utf-8?B?RnV0cm9uaWNzIERldmVsb3Blcg==?= | last post by:
I am trying to store a collection of custom types in a Properties.Settings file which I will be updating at run time and saving on exit of the program. I understand how to use the...
10
by: lpinho | last post by:
Hi all, I have a class (named for the example myObject) that can be of several types (int, string, float, etc), instead of using a object to define it's type I used a generic. public class...
26
by: raylopez99 | last post by:
Here is a good example that shows generic delegate types. Read this through and you'll have an excellent understanding of how to use these types. You might say that the combination of the generic...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.