How can I populate this complex List? - c#

I have a complex List data structure which i want to populate but i just cant seem to find a way to seed values to it.
List<Dictionary<List<int>, int>> l1 = new List<Dictionary<List<int>, int>>();
I want something like this,
l1.add( (1,2,3), 6);
I want to add a list of numbers and its sum.

Really not sure why you're doing that but if you really have to
var list = new List<Dictionary<List<int>, int>>();
list.Add(new Dictionary<List<int>, int> {{ new List<int> { 1, 2, 3 }, 6}});

I doubt you really need a list of dictionary of list. Still, you can write some kind of extension method:
public static ListHelpers
{
public void AddSum(this List<Dictionary<List<int>, int>> list, params int[] values)
{
list.Add(new Dictionary<List<int>, int> { values.ToList(), values.Sum() });
}
}
Then use it with:
l1.AddSum(1, 2, 3);

Related

Compare 2 dictionaries and return missing values

How would I compare these 2 dictionaries and return only the values missing?
The GetFileListFromBlob() function gets all file names and I'd like to know what is missing from the db.
Or is there a better way to get the missing values from these objects? Should I use different key/ value?
Dictionary<int, string> databaseFileList = new Dictionary<int, string>;
Dictionary<int, string> blobFileList = new Dictionary<int, string>;
int counter = 0;
foreach (string f in GetFileListFromDB())
{
counter++;
databaseFileList.Add(counter, f );
}
counter = 0;
foreach (string f in GetFileListFromBlob())
{
counter++;
blobFileList.Add(counter, f);
}
// How to compare?
Thank you
A HashSet<T> might be what you want (instead of a Dictionary<K,V>) - take this example:
var reference = new HashSet<string> {"a", "b", "c", "d"};
var comparison = new HashSet<string> {"a", "d", "e"};
When you now call ExceptWith on the reference set ...
reference.ExceptWith(comparison);
... the reference set will contain the elements "b" and "c" that do not exist in the comparison set. Note however that the extra element "e" is not captured (swap the sets to get "e" as the missing element) and that the operation modifies the reference set in-place. If that isn't wished for, the Except LINQ operator might be worth investigating, as was already mentioned in another answer.
The way I see it, you don't need counters at first (you can add them later).
You can use System.Collections.Generic.List<> type to go on.
List<int, string> databaseFileList = new List<string>(GetFileListFromDB());
List<int, string> blobFileList = new List<string>(GetFileListFromBlob());
//some code
Now if you want to get all items in both lists you can simply use Concat(...) method to unify them and then use Distinct() method to remove duplicate items:
List<string> allItems = databaseFileList.Concat(blobFileList).Distinct();
Now use Except(...) method to compare collections:
var missingItems1 = allItems .Except(databaseFileList);
//or
var missingItems1 = allItems .Except(blobFileList);
//or
//some other code
private void CompareDictionary()
{
var databaseFileList = new Dictionary<int, string>();
var blobFileList = new Dictionary<int, string>();
databaseFileList.Add(300, "apple");
databaseFileList.Add(500, "windows");
databaseFileList.Add(100, "Bill");
blobFileList.Add(100, "Bill");
blobFileList.Add(200, "Steve");
var result = databaseFileList.Where(d2 => !blobFileList.Any(d1 => d1.Key == d2.Key)).ToList();
}

C# sort a dictionary by value

I am sorting a dictionary, consisting of values & keys , by value. I have a hash of words and number of time used, that I want to order by number of time used.
There is a SortedList which is good for a single value , that I want to map it back to the word.
SortedDictionary orders by key, not value.
I could use a custom class, is there a better way.
I did some google searches but I can't find exactly what I am lookign for.
I found the answer
List<KeyValuePair<string, string>> BillsList = aDictionary.ToList();
BillsList.Sort(delegate(KeyValuePair<string, string> firstPair,
KeyValuePair<string, string> nextPair)
{
return firstPair.Value.CompareTo(nextPair.Value);
}
);
This should do it:
Dictionary<string, string> d = new Dictionary<string, string>
{
{"A","Z"},
{"B","Y"},
{"C","X"}
};
d.OrderBy(x=>x.Value).Select(x=>x.Key);
Will return C, B, A.
Here is using Linq and mapping the Count to the Word:
IDictionary<string, int> wordsAndCount = new Dictionary<string, int>
{
{"Batman", 987987987},
{"MeaningOfLife",42},
{"Fun",69},
{"Relaxing",420},
{"This", 2}
};
var result = wordsAndCount.OrderBy(d => d.Value).Select(d => new
{
Word = d.Key,
Count = d.Value
});
Result:

Store and access 2D data

If I have a data structure defined as:
Dictionary<KeyValuePair<int, int>, object> rangedValue;
and I populate it as such:
rangedValue = new Dictionary<KeyValuePair<int, int>, object>()
{
{ new KeyValuePair<int, int>(0,0), 424681 },
{ new KeyValuePair<int, int>(1,0), 1072301 },
{ new KeyValuePair<int, int>(2,0), 99111 },
{ new KeyValuePair<int, int>(3,0), 467874 },
{ new KeyValuePair<int, int>(0,1), 195066 },
{ new KeyValuePair<int, int>(1,1), 1171412 },
{ new KeyValuePair<int, int>(2,1), 0 },
{ new KeyValuePair<int, int>(3,1), 128504 }
}
and I want to iterate over it in a coordinated fashion, as in by (x, y) coordinate value and retrieve the value at that point, the best I can come up with is this:
foreach (var relativeXOffset in rangedValue.Keys.Select(kv => kv.Key).Distinct()) // Note distinct here, otherwise returns duplicates
{
foreach (var relativeYOffset in rangedValue.Keys.Select(kv => kv.Value).Distinct())
{
var myObject = rangedValue[new KeyValuePair<int, int>(relativeXOffset, relativeYOffset)];
// Do something with myObject...
}
}
This works for me but it also seems to be a bit rubbish. My requirements are to store an object against a set of coordinates and then be able to iterate over them in a coordinated fashion. Can anyone help with a nice solution, either on the storage or retrieval side (or, ideally, both)?
Create a specialized class with two coordinates and the data at this point:
public class XYD
{
int x;
int y;
object data;
}
Store these classes in a List:
List<XDY> xydList = new List<XYD();
xydList.Add(new XYD { x=0, y=0, data=424681 });
...
This creates a good storage and allows to iterate over your data. But search and retrieval times are O(n).
If you need faster acces you should create an additional dictionary:
Dictionary<Tuple<int,int>,XYZ> lookup;
which allows for a fast search of data given the coordinates.

Convert List<int>to List<List<int>>

Can i convert List<int>to List<List<int>> in c#?
When I use such construction
List<int>element=new List<int>();
List<List<int>>superElement= new List<List<int>>(element);
I get a fault,but can I do this in another way?
You can do it like this:
List<List<int>> superElement = new List<List<int>>();
superElement.Add(element);
List<int>element=new List<int>();
List<List<int>>superElement= new List<List<int>> { element };
That'll work. You can't pass the list in the constructor.
Try this :
var element = new List<int>();
var superElement = new List< List<int> >(){ element };
Yes. You can use the collection initializer
List<int> element = new List<int>();
List<List<int>> superElement = new List<List<int>> { element };
http://msdn.microsoft.com/en-gb/library/vstudio/bb384062.aspx
If you just want to initialize the List, then
List<List<int>>superElement= new List<List<int>>();
works; if you want it to contain one (empty) element initially then
List<List<int>>superElement= new List<List<int>>{element};
will do it.
Due to the fact I do not believe the other answers have really put in much effort to help, I am going to post what I believe to be a more complete and useful answer.
To start with, and for completeness I will show how to achieve what was actually trying to be done. To create a List of Lists you can do this:
List<int> element = new List<int>();
List<List<int>> superElement = new List<List<int>>();
superElement.Add(element);
But as it stands, it doesn't make a lot of sense why you would want to do this, and after some comment probing (hope it didn't hurt) we have discovered that you want to pair up an ID with a List of integers. I would suggest taking a different approach to this.
Personally, I would create a class to hold my data, and then create a single List for those items, like so:
public class MyData
{
public int ID {get; set;}
public List<int> MyValues {get;set;}
public MyData()
{
MyValues = new List<int>();
}
}
Then you can do this:
List<int> element = new List<int>();
MyData data = new MyData();
data.ID = 1;
data.MyValues = element;
List<MyData> superElement = new List<MyData>();
superElement.Add(data);
Which would allow querying like so:
MyData data1 = superElement.SingleOrDeafult(x => x.ID == 1);
List<int> element = data1.MyValues;
Assuming you have Linq available.
An alternate method could be to use a dictionary, like so:
Dictionary<int, List<int>> superElement = new Dictionary<int, List<int>>();
superElement.Add(1, element);
where 1 is an ID, which you can call like so:
List<int> element = superElement[1];

2-dimensional array with duplicated index key

i want to translate this line of code from php to asp.net
$subid[$value['parentid']][] = $value['id'];
i'm not familiar with asp.net data structure, i've tried arraylist but can't insert at [1], dictionary do not allow duplicated keys, anyone have ideas?
thanks
I'm not familiar with PHP (anymore) and SO is not a translation service, but you can use
List<Tuple<int, int>>
or
Lookup<int, int>
instead (assuming that your ids are ints).
var list = new List<Tuple<int, int>>();
list.Add(Tuple.Create(1, 1));
list.Add(Tuple.Create(1, 2));
list.Add(Tuple.Create(2, 3));
list.Add(Tuple.Create(2, 4));
list.Add(Tuple.Create(3, 5));
With Enumerable.ToLookup you can create a Lookup.
var lookup = list.ToLookup(t => t.Item1, t => t.Item2);
Find all products with parent-id = 1:
var parentID1 = lookup[1];
foreach (var value in parentID1)
Console.Write(value);
You can use a Dictionary with a little tweak to achieve what you want.
You create a dicionary like this:
Dictionary<string, List<string>> myDictionary = new Dictionary<string, List<string>>();
You add items to it like:
if(myDictionary.ContainsKey("myKey")) myDictionary["myKey"].Add("myItem");
else
{
myDictionary.Add("myKey", new List<string>(){"myItem"});
}
If you ask for a certain key, it will return a reference to the list with all related items.

Categories