C# Add variable value to list name - c#

Is it possible to add a variable to a list name when using it?
Something like this:
string id = "1"; //Could be 2
List<string> List1 = new List<string> {"1","11" };
List<string> List2 = new List<string> {"2","22" };
foreach (var element in List+id)
{ //code here }
IDs could be a dozen different values, so I didn't even try with regular if(). Would that be the only way?

Use a dictionary:
var dict = new Dictionary<string, List<string>>();
dict.Add("1", new List<string> {"1","11" });
dict.Add("2", new List<string> {"2","22" });
Then you can do
foreach (var element in dict[id])
{
}

Related

How can I extract a string out of an object that contains this string?

I created a Yaml that looks like this:
Directories:
- ./Libraries:
- DLLList.yml
- ./Output:
- None
Now I deserialized that yaml into a list of Objects:
List<object> allDirectoriesList = new List<object>();
List<string> allFileNames = new List<string>();
using (var reader = new StringReader(File.ReadAllText("./FileConfig.yml")))
{
allDirectoriesList = deserializer.Deserialize<dynamic>(reader)["Directories"] as List<Object>;
}
foreach (var directory in allDirectoriesList)
{
var directoryAsDictionary = (Dictionary<object, object>)directory;
List<object> list = directoryAsDictionary.Select(kvp => kvp.Value).ToList();
IEnumerable<string> _fileList = list.Select(i => i.ToString());
List<string> fileList = _fileList.ToList<string>();
for (int i = 0; i < fileList.Count(); i++)
{
var x = (string)list[i];
}
}
directory is an object of type Dictionary where I converted it into a List in this part:
var directoryAsDictionary = (Dictionary<object, object>)directory;
List<object> list = directoryAsDictionary.Select(kvp => kvp.Value).ToList();
This list contains 1 object of type string, where the filename is stored. But I can't get these strings out of the objects. If I cast them, or convert them ToString(), I always get "System.Collections.Generic.List`1[System.Object]", but it has to be "DLLList.yml" in this case
Assuming you are using YamlDotNet:
List<object> allDirectoriesList = new List<object>();
using (var reader = new StringReader(File.ReadAllText("./FileConfig.yml")))
{
allDirectoriesList = new DeserializerBuilder().Build().Deserialize<dynamic>(reader)["Directories"] as List<object>;
}
foreach (var directory in allDirectoriesList)
{
var directoryAsDictionary = (Dictionary<object, object>)directory;
List<object> list = directoryAsDictionary.SelectMany(kvp => (List<object>)kvp.Value).ToList();
List<string> _fileList = list.Select(Convert.ToString).ToList();
foreach(var file in _fileList)
Console.WriteLine($"Item: {file} found in {Convert.ToString(directoryAsDictionary.Keys.First())}");
}
Basically you were trying to turn the dictionary value to a string, but it was a List. By using SelectMany, it can flatten all the lists into one and use that. There were a few redundant casts, which I've also removed. For future reference, try to make your structures as simple as possible and deserialise them into structs/classes - you'll find this a lot easier that way.

How to have a list with different data types of lists in it as a sublists?

I want a method to return a list which contains two more list which are having two different data types, like :
List<List<object>> parentList = new List<List<object>>();
List<string> childList1 = new List<string>();
List<DataRow> childList2 = new List<DataRow>();
parentList.Add(childList1);
parentList.Add(childList2);
return parentList;
As per above code I am getting an error
The best overloaded method match for 'System.Collections.Generic.List>.Add(System.Collections.Generic.List)' has some invalid arguments
Please can anyone suggest me the best approach to handle this.
Thanks
What about creating an object of your class as like this?
public class myParent
{
public List<string> childList1 = new List<string>();
public List<DataRow> childList2 = new List<DataRow>();
}
public void someFun()
{
List<myParent> parentList = new List<myParent>();
myParent myParentObject = new myParent();
myParentObject.childList1 = new List<string>() { "sample" };
myParentObject.childList2 = new List<DataRow>() { };
parentList.Add(myParentObject);
}
I'm not sure why would you like to mix objects like this, but you could use ArrayList for this. Refer example below:
List<ArrayList> data = new List<ArrayList>();
data.Add(new ArrayList(){12, "12"}); //Added number and string in ArrayList
data.Add(new ArrayList() {"12", new object() }); //Added string and object in ArrayList
Update
In your case the using the array list like below could be better
var data = new ArrayList();
data.Add(new List<object>());
data.Add(new List<string>());
data.Add(new List<int>());

How to get the data inside a List<array>

example...
List<array> thisListOfArray = new List<array>();
List<string> thisArrayA= new List<string>();
List<string> gMaintenanceB = new List<string>();
thisArrayA.Add("ItemA1");
thisArrayA.Add("ItemA2");
thisArrayA.Add("ItemA3");
thisArrayB.Add("ItemB1");
thisArrayB.Add("ItemB2");
thisArrayB.Add("ItemB3");
thisListOfArray.Add(thisArrayA.ToArray());
thisListOfArray.Add(thisArrayB.ToArray());
I want to get every value that I have inputted inside the thisListOfArray.
you can get it following way. here is the code
List<string[]> thisListOfArray = new List<string[]>();
List<string> thisArrayA = new List<string>();
List<string> thisArrayB = new List<string>();
thisArrayA.Add("ItemA1");
thisArrayA.Add("ItemA2");
thisArrayA.Add("ItemA3");
thisArrayB.Add("ItemB1");
thisArrayB.Add("ItemB2");
thisArrayB.Add("ItemB3");
thisListOfArray.Add(thisArrayA.ToArray());
thisListOfArray.Add(thisArrayB.ToArray());
List<string> lstNewstring = new List<string>();
foreach (var strArray in thisListOfArray)
{
foreach (var str in strArray)
{
lstNewstring.Add(str);
}
}
MessageBox.Show(lstNewstring.Count.ToString());
Change your code like this:
List<List<string>> thisListOfArray = new List<List<string>>();
List<string> thisArrayA = new List<string>();
List<string> gMaintenanceB = new List<string>();
thisArrayA.Add("ItemA1");
thisArrayA.Add("ItemA2");
thisArrayA.Add("ItemA3");
gMaintenanceB.Add("ItemB1");
gMaintenanceB.Add("ItemB2");
gMaintenanceB.Add("ItemB3");
thisListOfArray.Add(thisArrayA);
thisListOfArray.Add(gMaintenanceB);
foreach (var itm in thisListOfArray.SelectMany(item => item))
{
MessageBox.Show(itm);
}
If you have:
List<string[]> listOfArray
string[] array
Add the array to the List with listOfArray.Add(array);
Not sure where you'll be getting array from.

LINQ get List<string> from List<List<string>> with any

Using LINQ, how I can retrieve list of list of item where match with another list?
Example:
List<string> data = new List<string>();
List<List<string>> datas = new List<List<string>>();
List<string> dataSearch = new List<string>();
dataSearch.Add("01");
dataSearch.Add("02");
data.Add("01");
data.Add("Book");
data.Add("9");
datas.Add(data);
data = new List<string>();
data.Add("02");
data.Add("Pen");
data.Add("2");
datas.Add(data);
data = new List<string>();
data.Add("03");
data.Add("Pencil");
data.Add("5");
datas.Add(data);
Expected Result in List<List<string>>:
List<string> ("01", "Book", "9")
List<string> ("02", "Pen", "2")
I try
var result = datas.Where(x => x[0].Contains(dataSearch)).ToList();
I got red underline in editor.
This is what you are looking for:
List<string> data = new List<string>();
List<List<string>> datas = new List<List<string>>();
List<string> dataSearch = new List<string>();
dataSearch.Add("01");
dataSearch.Add("02");
// same as your code
var result = datas.Where(i => dataSearch.Contains(i[0])).ToList();
If the three items in the List<List<string>> has a closely bound relationship it is better to create a class for this and then make a list of these objects.
Class StationaryItem
{
int ItemCode;
String ItemName;
float Price;
public StationaryItem(int Code, string ItemName,float Price)
{
this.ItemCode = Code;
this.ItemName = ItemName;
this.Price = Price;
}
}
public static void Main ()
{
List<StationaryItem> ItemList = new List<StationaryItems>
ItemList.Add( new StationaryItem(01,"Pen",20));
ItemList.Add( new StationaryItem(02,"Pencil",5));
//After you make a class like this you can use Linq to manuplate easily
}

LINQ: Get the data from the Dictionary in c#

I have a Dictionary> in c#:
Dictionary<string, List<string>> l_dictRawData =
new Dictionary<string, List<string>> {
{ "TamilNadu", new List<string>{ "Chennai", "Madurai" }},
{ "Andhra", new List<string>{"Hyderabad", "Secundarabad" }},
{ "Karnataka", new List<string>{"mysore", "Bangalore" }}
};
Then I have the InputList:
List<string> l_lstInput = new List<string> { "Hyderabad", "Secundarabad" };
The result will be the (i.e) if the dictionary l_dictRawData contains both "Hyderabad" and "Secundarabad" ,then select the key value:
string l_strOutPut = "Andhra";
Here is my code :
var Query = from l_strData in l_dictRawData
from l_strItem in l_lstInput
where l_strData .Value.Contains(l_strItem )
select new { CityName = l_strItem,
StateName = l_strData.Key
};
How can i get the ouput using LINQ in c#
Do you know that the list's data will be in the same order as the dictionary value's order? If so:
var result = l_dictRawData.Where(pair => pair.Value.SequenceEqual(l_lstInput))
.Select(pair => pair.Key)
.FirstOrDefault();

Categories