I want a List of OtherObjects all belonging to certain Objects.
Is it possible to create a List like so?
List<Object, List<OtherObject>>
Or should I create a new class and do?
List<NewClass>
Or should I do something else overall? The size is dynamic so I didn't want to use an array.
How can I achieve this?
You want a Dictionary<>, e.g.
Dictionary<Object, List<OtherObject>>
Where Object is the Key and List<OtherObject> is the Value
You can use Tuple<Object, List<OtherObject>> to achieve what you want.
Tuples is for composition of properties when you don't want to create special class. You can use Tuple<Object, AnotherObject, AnotherAnotherObject> if you need.
Your code will be something like:
List<Tuple<Object, List<OtherObject>>> list;
and work with it:
foreach(var tuple in list)
{
var object = tuple.Item1;
var innerList = tuple.Item2;
}
try Using
Dictionary<Object, List<OtherObject>>
Hope i helped
Related
With simpler dictionaries like this Dictionary<key,value> I know I can add an item to the dictionary like this:
if(!myDic.ContainKeys(key))
myDic[key] = value;
But how about a more complex dictionary like this:
Dictionary myDic<string, List<MyClass>>
where each key might have a list of values of my class? How do we add to that?
Here is a code snippet that I use for this:
// This is the list to which you would ultimately add your value
List<MyClass> theList;
// Check if the list is already there
if (!myDict.TryGetValue(key, out theList)) {
// No, the list is not there. Create a new list...
theList = new List<MyCLass>();
// ...and add it to the dictionary
myDict.Add(key, theList);
}
// theList is not null regardless of the path we take.
// Add the value to the list.
theList.Add(newValue);
This is the most "economical" approach, because it does not perform multiple searches on the dictionary.
The same way:
myDic[key] = new List<MyClass()>();
If the list is already there and you want to add to it:
myDic[key].Add(new MyClass());
You can use TryGetValue method:
List<MyClass> list;
if (myDic.TryGetValue(key, out list))
list.Add(value); // <- Add value into existing list
else
myDic.Add(key, new List<MyClass>() {value}); // <- Add new list with one value
If the value to add is an item for the list, you can do:
if(!myDic.Keys.Contains(key)) {
myDic[key] = new List<MyClass>();
}
myDic[key].Add(value);
This is my generic list. I would like to return the object CompanyEmail by finding the object based on the index. How do I do this ?
List<CompanyEmail> companyEmail = (List<CompanyEmail>)ViewState["companyEmail"];
try:
List<Data> data = new List<Data>();
Data temp = data[1];
in your list:
companyEmail[index];
why on index, you may use the Dictionary Class (it's generic too). http://msdn.microsoft.com/en-us/library/xfhwa508.aspx
hope I got you right.
This should do the trick:
http://msdn.microsoft.com/en-us/library/x1xzf2ca.aspx
Use:
List<T>.FindIndex(Predicate)
Is it possible to convert a a IEnumerable<KeyValuePair<string,string>> of KeyValuePair to an anonymous type?
Dictionary<string, string> dict= new Dictionary<string, string>();
dict.add("first", "hello");
dict.add("second", "world");
var anonType = new{dict.Keys[0] = dict[0], dict.Keys[1] = dict[1]};
Console.WriteLine(anonType.first);
Console.WriteLine(anonType.second);
********************output*****************
hello
world
The reason i would like to do this is because I am retrieving an object from a webservice that represents an object that does not exist in the wsdl. The returned object only contains a KeyValuePair collection that contains the custom fields and their values. These custom fields can be named anything, so i cant really map an xml deserialization method to the final object i will be using (whose properties must be bound to a grid).
*Just because I used Dictionary<string,string> does not mean it is absolutely a dictionary, i just used it for illustration. Really its an IEnumerable<KeyValuePair<string,string>>
Ive been trying to thing of a way to do this, but am drawing a blank. This is c# .NET 4.0.
You could use the ExpandoObject, it is based on a dictionary.
I think there are a lot of ways to achieve this, but actually converting it in the same Dictionary seems a bit odd to do.
One way to accomplish this, by not actually converting everyting is the following:
public class MyDictionary<T,K> : Dictionary<string,string> // T and K is your own type
{
public override bool TryGetValue(T key, out K value)
{
string theValue = null;
// magic conversion of T to a string here
base.TryGetValue(theConvertedOfjectOfTypeT, out theValue);
// Do some magic conversion here to make it a K, instead of a string here
return theConvertedObjectOfTypeK;
}
}
ExpandoObject is the best option, which I believe is a wrapper around some XML. You could also use an XElement:
var result = new XElement("root");
result.Add(new XElement("first", "hello"));
result.Add(new XElement("second", "world"));
Console.WriteLine(result.Element("first").Value);
Console.WriteLine(result.Element("second").Value);
foreach (var element in result.Elements())
Console.WriteLine(element.Name + ": " + element.Value);
I haven't used ExpandoObject, so I'd try that first because I understand it does exactly what you want and is also something new and interesting to learn.
I'm trying to locate all the keys in one Dictionary that are not in another Dictionary. Obviously, I can do this using a nested loop, but I'm trying to learn LINQ at the moment and I was wondering if I might use it to accomplish this task?
Here's what I have so far:
Dictionary<string, List<string>> DBtables = this.CollectTableListings();
var generic = from Dictionary<string,List<string>> tab
in DBtables
where !_tables.ContainsKey(???)
select tab;
Any idea what should go in place of the question marks (or perhaps instead of the entire where clause)?
You can do:
var resultKeys = DBTables.Keys.Except( _tables.Keys );
The Except() method is essentially the same as the minus operations in SQL - it returns all items from the first collection excluding those in the second. Since dictionaries expose their keys, you can compute their difference that way.
The Except() operator uses the default equality for the type, but there is also an overload which allows you to specify your own IEqualityComparer to override the semantics of how to compare values. In your example, you probably don't need that - but it's nice to know it there.
Dictionary<string, List<string>> dictOne = ...
Dictionary<string, List<string>> dictTwo = ...
var missingKeys = dictOne.Keys.Where(x => !dictTwo.ContainsKey(x));
Dictionary<string, List<string>> dictionary = this.CollectTableListings();
Dictionary<string, List<string>> otherDictionary = getOtherTable();
var keys = from key in dictionary.Keys
where !otherDictionary.Keys.Contains(key)
select key;
(But LBuskin's answer is much better)
have a look at the Except extension method. HTH.
If you wanted to use query syntax I would do something akin to below:
var keys = from d1 in dictionary1
select d1.Key;
var items = from d2 in dictionary2
where d2.Key in keys
select d2;
foreach(var item in items)
{
}
Suppose I have a Dictionary like so:
Dictionary<string, Stream>
How can I get a list (or IEnumerable or whatever) of JUST the Keys from this dictionary? Is this possible?
I could enumerate the dictionary, and extract the keys one by one, but I was hoping to avoid this.
In my instance, the Dictionary contains a list of filenames (file1.doc, filex.bmp etc...) and the stream content of the file from another part of the application.
KeyCollection Dictionary(TKey, TValue).Keys
Dictionary(TKey, TValue).Keys
Typically you can discover these things through code-completion/IntelliSense.
Similarly, there is a Values property:
Dictionary<T,T>.Keys returns a KeyCollection. This has the IEnumerable interface.
so...
foreach(string key in Dictionary<string,Stream>.Keys)
{
}
public IEnumerable<long> ReturnSomeKeys()
{
var foo = new Dictionary<long, string>();
return foo.Keys;
}
This does what you want.