Create number of new class objects from dictionary count - c#

int proprtyCount = dictionary.Keys.Count;
foreach (KeyValuePair<object, object> pair in dictionary)
{
ClassCustom obj1 =new ClassCustom(pair.Key, pair.Value);
}
I need to create number objects using dictionary.keys.count and pass those objects to some collection class.
i have to pass objects like below to collection (eg.dictionary key count is 3 in this case)
SomeCollection collection =new SomeCollection(obj1,obj2,obj3);

Why don't you assign it to a list?
int proprtyCount = dictionary.Keys.Count;
var classCustomList = new List<ClassCustom>();
foreach (KeyValuePair<object, object> pair in dictionary)
{
classCustomList.Add(new ClassCustom(pair.Key, pair.Value));
}
SomeCollection collection = new SomeCollection(classCustomList);
Have the SomeCollection class initialize a list of type classCustomList in it's constructor.
Update: If it's some sort of collection class, maybe try doing something similar to
int proprtyCount = dictionary.Keys.Count;
var conditions = new PropertyCondition[propertyCount];
int index = 0;
foreach (KeyValuePair<object, object> pair in dictionary)
{
conditions[i] = new PropertyCondition(pair.Key, pair.Value));
index++;
}
var conditionEnabledButtons = new AndCondition(conditions);
There's an overload with type array
Eg.
var conditions = new PropertyCondition[3];
conditions[0] = new PropertyCondition(AutomationElement.IsEnabledProperty, true);
conditions[1] = new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Button);
var conditionEnabledButtons = new AndCondition(conditions);

Related

C#: Intersect a dictionary with a list. Return dictionary item after match

how can I safety return the dictionary item which matches with the item from the list?
static void Test()
{
var dict = new Dictionary<string, string>();
dict.Add("license1", "123");
dict.Add("license2", "456");
dict.Add("license3", "789");
var list = new List<string>();
list.Add("444");
list.Add("111");
list.Add("123");
var result = dict.Values.Intersect(list);
//result should be only the matching item as a dictionary for dict -> for this example = "license1, 123"
}
Because the dictionary isn't arranged helpfully I think I might do:
var h = list.ToHashSet();
var result = dict.Where(kvp => h.Contains(kvp.Value));

How to get value of a specific value of a list in C#

var ctsDB = mooe.Files66.ToList();
Dictionary<string, string> mappedfields = new Dictionary<string, string>();
Dictionary<string, string> ctsfieldsValue = new Dictionary<string, string>();
for (int i = 0; i < ctsDB.Count; i++)
{
foreach(var item in mappedfields) {
// this line returns the item.key string not the value of it.
// item.key is the column name
var rowValue = mooe.Files66.Select(k = >item.Key).ToList();
// ctsfieldsValue.Add(item.Value, rowValue);
ctsfieldsValue.ToList();
}
}
I want to iterate through ctsDB List and get the row value of a specific
column like this:
if ctsDB [i] = fileID Field612 Fiel613
and I have these column names in the value field of ctsfieldsValue.
I want to iterate on ctsDB[i] to get the value of column Field612 only.
Can anyone provide a thought?
var ctsDB = mooe.Files66.ToList();
var mappedfields = new Dictionary<string, string>(); // I assume this is not empty in your real code.
var ctsfieldsValue = new List<Dictionary<string, string>>();
foreach (var row in ctsDB)
{
var d = new Dictionary<string, string>();
foreach (var mapping in mappedfields)
{
var v = row[mapping.Key]; //throws if not found
d[mapping.Value] = v;
}
ctsfieldsValue.Add(d);
}

Create an array of list

I want to create a array of list which will contain a string and a list of arrays.
example:
I want like this one.
list(0) --- string value list(0) ---list(0) - string value
list(0) ----list(1) - string value
list(1) --- string value list(1) ---list(0) - string value
list(1) ----list(1) - string value
and so on..
how will i declare?
i tried:
List<List<String>> list = new List<List<string>>(); // but it didn't work.
List<string[]> arrayList = new List<string[]>(); // again it didn't work..
is this possible to declare?
if so how?
Isnt this a Dictionary<string, string[]>?
var x = new Dictionary<string, string[]>();
x.Add("string1", new string[] {"a", "b", "c"})
Then you can have a list of that dictionary.
var list = new List<Dictionary<string, string[]>>();
list.Add(x);
Does this work for you?
public class Tree<T> : List<Tree<T>>
{
public Tree(T value) { this.Value = value; }
public T Value { get; set; }
}
It's not an array, but a list, but it's much the same structure.
You can then assign it like this:
var trees = new []
{
new Tree<string>("Branch 1")
{
new Tree<string>("Leaf 1.1"),
new Tree<string>("Leaf 1.2"),
},
new Tree<string>("Branch 2")
{
new Tree<string>("Leaf 2.1"),
new Tree<string>("Leaf 2.2"),
},
};
As I can see in your data structure you've asked for A List containing two List's and all of them are of same string type then you should go with Dictionary. As a List can of of single type and you can add a single value to it at a time. Try Dictionary,
Dictionary<string, string> dictionary = new Dictionary<string, string>();
or if you want a Dictionary containing List of string,
Dictionary<List<string>, List<string>> dictionary = new Dictionary<List<string>, List<string>>();
try this
List<List<String>> str_2d_list = new List<List<String>>();
List<String> l1 = new List<string>();
l1.Add("l1.string1");
l1.Add("l1,string2");
List<String> l2 = new List<string>();
l2.Add("l2.string1");
l2.Add("l2,string2");
str_2d_list.Add(l1);
str_2d_list.Add(l2);
if you want to create an array of a string and a list, use the second way in the code. but if you want a list of list use first way in the code.
using System;
using System.Collections.Generic;
namespace ConsoleApplication1
{
internal class Program
{
private static void Main(string[] args)
{
// an example of list of strings
List<string> names = new List<string>();
names.Add("Mike");
names.Add("Sarah");
List<string> families = new List<string>();
families.Add("Ahmadi");
families.Add("Ghasemi");
// 1st way
List<List<string>> outsideList = new List<List<string>>();
outsideList.Add(names);
outsideList.Add(families);
// 2nd way
Dictionary<string, List<string>> d = new Dictionary<string, List<string>>();
d.Add("first", names);
d.Add("second", families);
// how to access list<list<>>
foreach (List<string> list in outsideList)
{
foreach (string s in list)
Console.WriteLine(s);
}
// how to access list inside dictionary
foreach (List<string> list in d.Values)
{
foreach (string s in list)
Console.WriteLine(s);
}
}
}
}

Add to dictionary some params from request

I want to get some params from Request
I need from Request.Params all params with text contains "txt" I have more type of text structure:
"ctl00$cphMain$repDelTypes$ctl00$ucDel$txtPhone"
"ctl00$cphMain$repDelTypes$ctl00$ucDel$txtPhone2"
"ctl00$cphMain$repDelTypes$ctl00$ucDel$txtPhone3"
"ctl00$cphMain$repDelTypes$ctl00$ucDel$txtAdr1"
"ctl00$cphMain$repDelTypes$ctl00$ucDel$txtAdr2"
"ctl00$cphMain$repDelTypes$ctl00$ucDel$txtAdr3"
how Get value all text after "txt"
var dictionary = new Dictionary<string, string>();
foreach (var key in Request.Params.AllKeys)
{
if (key.ToString().Contains("txt"))
{
// add to dictionary name and value
// dictionary.Add("name", "val");
}
}
You can do this:
var dictionary = new Dictionary<string, string>();
foreach (var key in Request.Params.AllKeys)
{
if (key.ToString().Contains("txt"))
{
int index = Request.Params[key].LastIndexOf("txt");
Dictionary.Add(key, Request.Params[key].SubString(index));
}
}
Are you asking how to add to the dictionary?
var dictionary = new Dictionary<string, string>();
foreach (var key in Request.Params.AllKeys)
{
if (key.ToString().Contains("txt"))
{
//get the text after "txt"
var index = Request.Params[key].LastIndexOf("txt");
var val = Request.Params[key].SubString(index);
Dictionary.Add(key, val);
}
}
var dictionary = new Dictionary<string, string>();
foreach (var key in Request.Params.AllKeys)
{
if (key.ToString().Contains("txt"))
{
// add to dictionary name and value
dictionary.Add(key.Split(new string[]{"txt"}, StringSplitOptions.None)[1], Request.Params[key]);
}
}

Query a Dictionary of Dictionaries?

Please can you advise me on how to query a Dictionary of Dictionaries, and/or a Dictionary of List?
private Dictionary<string, Dictionary<DateTime, double>> masterDict= new Dictionary<string, Dictionary<DateTime, double>>();
Private Dictionary<string, List<DateTime>> masterList= new Dictionary<string, List<DateTime>>();
I know if I do the following, I get a list of the dictionaries contained in masterDict, but I'm not sure how to get at the values of those dictionaries.
foreach (var kvp in masterDictMethod())
{
Console.WriteLine("Key = {0}, Value = {1}",
kvp.Key, kvp.Value);
}
Thanks for looking ;)
In you foreach kvp.Value is the inner dictionary of every masterDict entry i.e. Dictionary<DateTime, double>
So, just foreach also over kvp.Value and you will get the inner values.
e.g.
foreach (var kvp1 in masterDictMethod())
{
Console.WriteLine("Key = {0}, Inner Dict:", kvp1.Key);
foreach (var kvp2 in kvp1.Value)
{
Console.WriteLine("Date = {0}, Double = {1}", kvp2.Key, kvp2.Value);
}
}
Use masterDict.Values
This one is:
var masterDictionary = new Dictionary<string, Dictionary<DateTime, double>>();
var query =
from kvp1 in masterDictionary
from kvp2 in kvp1.Value
select new {TheString = kvp1.Key, TheDate = kvp2.Key, TheDouble = kvp2.Value };
foreach(var x in query)
{
Console.WriteLine("{0} {1} {2}", x.TheString, x.TheDate, x.TheDouble);
}
And then the other one is:
var masterList= new Dictionary<string, List<DateTime>>();
var query =
from kvp in masterList
from val in kvp.Value
select new {TheString = kvp.Key, TheDate = val);
foreach(var x in query)
{
Console.WriteLine("{0} {1}", x.TheString, x.TheDate);
}
foreach (var key in masterDict.Keys)
{
var nestedDict = masterDict[key];
}
You asked about lists, dictionaries and dictionaries containing other dictionaries.
I had a similar topic recently, where I wanted to have a queryable dictionary (i.e. an extension method which allows to pass a query expression as lambda parameter), that you can use like:
var result = myDictionary.QueryDictionary(w => myList.Any(a => a == w.Key));
The purpose of this code line is to check if any key of the dictionary is contained in myList.
So what I did is this, I wrote the following extension method:
// extension method using lambda parameters
public static Dictionary<string, T> QueryDictionary<T>(
this Dictionary<string, T> myDict,
Expression<Func<KeyValuePair<string,T>, bool>> fnLambda)
{
return myDict.AsQueryable().Where(fnLambda).ToDictionary(t => t.Key, t => t.Value);
}
It can be used for every dictionary which has keys of type string and items of every object type T.
Now you can easily write queries by passing a lambda expression, as in the following example:
var list1 = new List<string>() { "a", "b" };
var myDict = new Dictionary<string, object>();
myDict.Add("a", "123"); myDict.Add("b", "456"); myDict.Add("c", "789");
var result = myDict.QueryDictionary(w => list1.Any(a => a == w.Key));
The result will contain items a and b, because they are contained in list1.
You can also query a dictionary of dictionaries, here's a C# example for LinqPad, but it can be used as a console application as well (just comment out the .Dump() statements and replace them by Console.WriteLine(...) statements):
void Main()
{
// *** Set up some data structures to be used later ***
var list1 = new List<string>() { "a", "b", "d" }; // a list
var myDict = new Dictionary<string, object>(); // the dictionary
myDict.Add("a", "123"); myDict.Add("b", "456"); myDict.Add("c", "789");
var myDict2 = new Dictionary<string, object>(); // 2nd dictionary
myDict2.Add("a", "123"); myDict2.Add("b", "456"); myDict2.Add("c", "789");
myDict.Add("d", myDict2); // add 2nd to first dictionary
// *** 1. simple query on dictionary myDict ***
var q1 = myDict.QueryDictionary(w => list1.Any(a => a == w.Key));
q1.Dump();
// *** 2. query dictionary of dictionary (q3 contains result) ***
var q2 =
(Dictionary<string, object>)q1.QueryDictionary(w => w.Key.Equals("d")).First().Value;
var q3 = q2.QueryDictionary(w => w.Key.Equals("b"));
q3.Dump();
}
// *** Extension method 'QueryDictionary' used in code above ***
public static class Extensions
{
public static Dictionary<string, T> QueryDictionary<T>(
this Dictionary<string, T> myDict,
Expression<Func<KeyValuePair<string, T>, bool>> fnLambda)
{
return myDict.AsQueryable().Where(fnLambda).ToDictionary(t => t.Key, t => t.Value);
}
}
Since this solution is using Generics, you can pass any lambda expression as search parameter, so it is very flexible.

Categories

Resources