473,237 Members | 1,122 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,237 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 3966
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: jianzs | last post by:
Introduction Cloud-native applications are conventionally identified as those designed and nurtured on cloud infrastructure. Such applications, rooted in cloud technologies, skillfully benefit from...
0
by: abbasky | last post by:
### Vandf component communication method one: data sharing ​ Vandf components can achieve data exchange through data sharing, state sharing, events, and other methods. Vandf's data exchange method...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
by: fareedcanada | last post by:
Hello I am trying to split number on their count. suppose i have 121314151617 (12cnt) then number should be split like 12,13,14,15,16,17 and if 11314151617 (11cnt) then should be split like...
0
Git
by: egorbl4 | last post by:
Скачал я git, хотел начать настройку, а там вылезло вот это Что это? Что мне с этим делать? ...
1
by: davi5007 | last post by:
Hi, Basically, I am trying to automate a field named TraceabilityNo into a web page from an access form. I've got the serial held in the variable strSearchString. How can I get this into the...
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
by: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
0
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...

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.