Use Variable for Control Name [duplicate] - c#

This question already has answers here:
C#: how to get an object by the name stored in String?
(4 answers)
Get value of a variable using its name in a string
(2 answers)
Getting variable by name in C#
(1 answer)
Closed 3 years ago.
I have created multiple List and want to use each individual List when I have a variable name.
For example:
private List<string> listAlabama = new List<string>();
private List<string> listTexas = new List<string>();
// fill Lists with values
//Call Method to assign state to correct list
AssignNameToList("Alabama");
private void AssignNameToList(string state)
{
// Assign variable to the correct List e.g
sring tempFindList="list"+state;
//Use the right List
string tempVal=tempFindList[0]???
// should be listAlabama
}
Below is the solution I came up with using a Dictionary
var dictionary = new Dictionary<string, List<string>>();
dictionary.Add("Alabama", listAlabama);
dictionary.Add("Texas", listTexas);
switch (tempState)
{
case "Alabama":
List<string> value = dictionary["Alabama"];
Console.WriteLine(value);
string[] tempArray = value[totalPopulationIdx].Split(',');

Related

How to find duplicate keys from a List<KeyValuePair<byte[], string>> fileHashList = new List<KeyValuePair<byte[], string>>(); [duplicate]

This question already has answers here:
Group by array contents
(1 answer)
Easiest way to compare arrays in C#
(19 answers)
Closed 2 years ago.
I've a lsit of type List<KeyValuePair<byte[], string>> fileHashList = new List<KeyValuePair<byte[], string>>();
foreach (string entry in results)
{
FileInfo fileInfo = new FileInfo(Path.Combine("DirectoryPath"), entry));
using (var md5 = MD5.Create())
{
using (var stream = File.OpenRead(fileInfo.FullName))
{
var hash = md5.ComputeHash(stream);
fileHashList.Add(new KeyValuePair<byte[], string>(hash, fileInfo.FullName));
}
}
}
I need to find all the duplicate keys in this list.
I tried this but doesn't work in my case, I get "Enumeration yielded no results" even though I've same keys!
Let me know if any additional data is needed
Thanks

Parsing string into key value pairs C# [duplicate]

This question already has answers here:
How can I deserialize JSON with C#?
(19 answers)
Closed 2 years ago.
I have method where I call another API. From
var activeCustomers = await response.Content.ReadAsStringAsync();
I get string which contains [timestamp, value] objects:
{"values":[[1298937600000,1],[1459468800000,16],[1462060800000,527],[1464739200000,173],[1467331200000,132],[1470009600000,166],[1472688000000,151],[1475280000000,172],[1477958400000,139],[1480550400000,129],[1483228800000,116],[1485907200000,133],[1488326400000,180],[1491004800000,227],[1493596800000,281],[1496275200000,263],[1498867200000,230],[1501545600000,326],[1504224000000,403],[1506816000000,442],[1509494400000,1019],[1512086400000,650],[1514764800000,708],[1564617600000,2614],[1567296000000,2527],[1569888000000,3144],[1572566400000,3075],[1575158400000,2541],[1577836800000,2246],[1580515200000,2456],[1583020800000,885]]}
I want to parse these values into key value pairs, but I am not sure what's the most optimal way for that.
I tried removing beginning and ending of string and cast it as object but it stays as one big string inside the ienumerable:
int index = activeCustomers.IndexOf(":");
if (index > 0)
activeCustomers = activeCustomers.Substring(index + 1);
activeCustomers = activeCustomers.Remove(activeCustomers.Length - 1);
var results = ((IEnumerable) activeCustomers).Cast<object>();
I also tried making regex for that but I am not very comfortable with that.
This just a JSON with array of arrays, which can be easily deserialized using Json.NET
var result = JsonConvert.DeserializeObject<Root>(activeCustomers);
or System.Text.Json
var result = JsonSerializer.Deserialize<Root>(activeCustomers);
Where Root is
public class Root
{
public long[][] values { get; set; }
}
Then you can map the values property to any desired structure using Select method
var pairs = result.values.Select(v => new { timestamp = v[0], value = v[1] }).ToList();

Best way to map one value to many [duplicate]

This question already has answers here:
C# dictionary - one key, many values
(15 answers)
Multi Value Dictionary?
(10 answers)
Dictionary one key many values in code c#
(4 answers)
Closed 3 years ago.
I was wondering about the best way to map one value to many in a dictionary (or some other structure) in C#.
What I wanted to do is something like this:
public GenreToEntity = new Dictionary<string, string[]>()
{
{ "filmes", ["Filme"] },
{ "programas", ["Jornalismo", "Variedade", "Série/seriado"] }
};
But it should be static, so I don't want to add values line by line.
Is that possible?
I got it! The missing part was what #itsme86 suggested:
public static Dictionary<string, List<string>> EntityToGenre = new Dictionary<string, List<string>>()
{
{ "filmes", new List<string>() {"Filme"} },
{ "novelas", new List<string>() {"Novela"} },
{ "programas", new List<string>() {"Jornalismo", "Variedade", "Série/seriado", "Outros" } }
};

Using a variable inside a member of an object [duplicate]

This question already has answers here:
Get property value from string using reflection
(24 answers)
Closed 8 years ago.
I am pulling several elements of data out of an object in C#. They are all in the same 'place' within the object, as in:
objectContainer.TableData.Street.ToString());
objectContainer.TableData.City.ToString());
objectContainer.TableData.State.ToString());
objectContainer.TableData.ZipCode.ToString());
I would LIKE to use a foreach loop to pull them all and be able to add more by adding to the array.
string[] addressFields = new string[] { "Street", "City", "State", "ZipCode" };
foreach(string add in addressFields)
{
objectContainer.TableData.{add}.ToString());
}
Can this be done, and if so, what is the correct procedure?
You would need to use reflection to achieve this:
var type = objectContainer.TableData.GetType();
foreach(var addressFieldName in addressFieldNames)
{
var property = type.GetProperty(addressFieldName);
if(property == null)
continue;
var value = property.GetValue(objectContainer.TableData, null);
var stringValue = string.Empty;
if(value != null)
stringValue = value.ToString();
}
Please note: This code is pretty defensive:
It will not crash if no property with the specified name exists.
It will not crash if the value of the property is null.
You can use Reflection to do this.
string[] addressFields = new string[] { "Street", "City", "State", "ZipCode" };
foreach(string add in addressFields)
{
var myVal = objectContainer.TableData.GetType().GetProperty(add).GetValue(objectContainer.TableData).ToString();
}
Note that this doesn't allow for array values that don't have a corresponding property on objectContainer.TableData.

How to get string list of Enum descriptions? [duplicate]

This question already has answers here:
Enum ToString with user friendly strings
(25 answers)
Closed 4 years ago.
How can I get a List of an Enum's values?
For example, I have the following:
public enum ContactSubjects
{
[Description("General Question")]
General,
[Description("Availability/Reservation")]
Reservation,
[Description("Other Issue")]
Other
}
What I need to be able to do is pass ContactSubject.General as an argument and it returns the List of the descriptions.
This method needs to work with any Enum, not just ContactSubject (in my example). The signature should be something like GetEnumDescriptions(Enum value).
Something like that may work:
private static IEnumerable<string> GetDescriptions(Type type)
{
var descs = new List<string>();
var names = Enum.GetNames(type);
foreach (var name in names)
{
var field = type.GetField(name);
var fds = field.GetCustomAttributes(typeof(DescriptionAttribute), true);
foreach (DescriptionAttribute fd in fds)
{
descs.Add(fd.Description);
}
}
return descs;
}
however you may review some logic there: such as is it ok to start of names? how are you going to handle multiple Description attributes? What if some of them are missing - do you want a name or just skip it like above? etc.
just reviewed your question. For the VALUE you would have something like that:
private static IEnumerable<string> GetDescriptions(Enum value)
{
var descs = new List<string>();
var type = value.GetType();
var name = Enum.GetName(type, value);
var field = type.GetField(name);
var fds = field.GetCustomAttributes(typeof(DescriptionAttribute), true);
foreach (DescriptionAttribute fd in fds)
{
descs.Add(fd.Description);
}
return descs;
}
however it is not possible to place two Description attributes on single field, so I guess it may return just string.

Categories