can this value be output with inline code in c#? - c#

Please consider the following inline code:
string.Join(",", context.Request.Headers.ToArray())
If the Headers structure above were a Dictionary(string, string), the code above would output the following:
[MyHeaderKey1, MyHeaderVal1],[MyHeaderKey2, MyHeaderVal2]
However, the Dictionary value is a string[] so the following gets output instead:
[MyHeaderKey1, System.String[]],[MyHeaderKey2, System.String[]]
I need to be able to generate output like the first code example but against the Dictionary with the string[] value. It's ok if I only take the first item of the Dictionary - string[] value. Can this be done with inline C#?

Yes. Use Linq Select.
string.Join(",", context.Request.Headers.Select(x => string.Format("[{0}, {1}]", x.Key, FormatThisArray(x.Value))))
EDIT: Since OP mentioned that the value is string[], the default x.Value as described above may not produced desired output. I'm not sure how OP would format the value of the dictionary item and assuming FormatThisArray is a function that formats the array.

You need to do something like this:
var result =
string.Join(",",
context.Request.Headers.Select(x =>
string.Format(
"[{0},{1}]",
x.Key,
"(" + string.Join(",", x.Value) + ")")));
This joins the individual items inside each string[] with a , and puts them between brackets.
Output would look like this:
[MyHeaderKey1,(v1,v2,v3)],[MyHeaderKey2,(v4,v5,v6)]

If you just need the fist value:
string.Join(",", context.Request.Headers.Select(d=>new {d.Key,Value=d.Value.FirstOrDefault()}));

Related

Flat dictionary to JSON string?

I have a dictionary like the below:
private readonly Dictionary<string, string> _packetData;
I try and convert a dictionary to json, I do json2dictionary also which just converts it to a flat dictionary, but this is in reverse, converting from dictionary2json.
public string GetJson()
{
var entries = _packetData.Select(d => string.Format("\"{0}\": [{1}]", d.Key, string.Join(",", d.Value)));
return "{" + string.Join(",", entries) + "}";
}
I've noticed that it doesn't wrap strings with double quotes each end, instead it does this.
{"test":test123}
What am I doing wrong?
There are no quotes in your output, because you haven't included quotes in your format string, just as you have with the key. I have removed your brackets ([ and ]), because they indicate an array value in JSON, and your dictionary has string values, so no need for string.Join().
var entries = _packetData.Select(d => string.Format("\"{0}\": \"{1}\"", d.Key, d.Value));
I would also recommend that you use the Newtonsoft's excellent Json.NET library, which you can find on nuget. Using a library instead of rolling your own implementation is more reliable and often more secure, and often means that you don't need to write as much code. In this case, it would be as simple as:
JsonConvert.SerializeObject(_packetData);
https://www.newtonsoft.com/json/help/html/SerializeDictionary.htm
var entries = _packetData.Select(d => string.Format("\"{0}\": [\"{1}\"]", d.Key, string.Join(",", d.Value)));

How to turn a dictionary<string, int> elements into strings. c#

I'm currently working on a game in which the top 5 highscores can be displayed on a highscores page.
Currently i have a dictionary of type [string, int] which will store the user's name and score respectively.However, i'm having trouble creating a method that will take all 5 dictionary elements in the format of {"name", 20} and assign each element to a string.
For example, dictionary element[0] contains the value {sam, 20}. I would like to assign this element to a string that would read "sam 20".
At the moment i have a method which will return the top5 highscores but my problem occurs when turning these values into strings from dictionary elements.
Any help would be appreciated and if you have any questions, please don't hesitate to ask.
Thanks in advance.
You can use .Select() and string interpolation to build out a projected string list:
var formattedStrings = dict
.OrderByDescending(x => x.Value)
.Select(x => $"{x.Key} {x.Value}").ToList();
Since Dictionary<TKey, TValue> implements IEnumerable<KeyValuePair<TKey, TValue>>, we can easily use LINQ to both order and project our key/value pairs before interpolating them into a new string.
This also allows for more flexible querying before projecting your list.
try this.
var answer= string.Join(",", map.Select(s => s.Key + " " +s.Value).ToArray());

using lambda, how to apply an existing function to all elements of a list?

Excuse me, a quick question:
I have a list of strings, string are full paths of some files. I would like to get only the filename without the path neither the extension for each string (and to understand lambda more)
Based on the lambda expression in How to bind a List to a DataGridView control? I am trying something like the below:
FilesName = Directory.GetFiles(fbd.SelectedPath).ToList(); // full path
List<string> FilesNameWithoutPath = AllVideosFileNames.ForEach(x => Path.GetFileNameWithoutExtension(x)); // I want only the filename
AllVideosGrid.DataSource = FilesNameWithoutPath.ConvertAll(x => new { Value = x }); // to then bind it with the grid
The error is:
Can not convert void() to List of string
So I want to apply Path.GetFileNameWithoutExtension() for each string in FilesName. And would appreciate any extra description on how Lamba works in this case.
ForEach will execute some code on each item in your list, but will not return anything (see: List<T>.ForEach Method). What you want to do is Select the result of the method (see: Enumerable.Select<TSource, TResult> Method), which would look something like:
List<string> FilesNameWithoutPath = AllVideosFileNames
.Select(x => Path.GetFileNameWithoutExtension(x))
.ToList();
You are using List<T>.ForEach method which takes each element in the list and applies the given function to them, but it doesn't return anything. So what you are doing basically is getting each file name and throwing them away.
What you need is a Select instead of ForEach:
var fileNamesWithoutPath = AllVideosFileNames
.Select(x => Path.GetFileNameWithoutExtension(x))
.ToList();
AllVideosGrid.DataSource = fileNamesWithoutPath;
This will project each item, apply Path.GetFileNameWithoutExtension to them and return the result, then you put that result into a list by ToList.
Note that you can also shorten the Select using a method group without declaring a lambda variable:
.Select(Path.GetFileNameWithoutExtension)

How to easily remove part of string from string array in c#

I am using following code:
var names = ConfigurationManager.AppSettings.AllKeys.Where(k => k.StartsWith("name"));
and i get keys like: name1, name2, name16, name18.
Now i want to create another array which will remove name and just keep 1,2,16,18. Is there any easy way to do this in above code itself? Or do it seperatly?
You can directly
ConfigurationManager.AppSettings.AllKeys.Where(k => k.StartsWith("name")).Select(a => a.Replace("name",""));
I think your code is good enough. Just a little bit of performance improve by using substring as it's straightforward operation to remove prefix:
var prefix = "name"; // could be a parameter or used as const; just for example
var nums = ConfigurationManager.AppSettings.AllKeys.Where(s => s.StartsWith(prefix)).Select(s => s.Substring(prefix.Length)).ToArray();
Try this:
var names = ConfigurationManager.AppSettings.AllKeys.Where(k => k.StartsWith("name")).Select(p => p.Replace("name", ""));
Use:
var namesWithoutPrefix = names.Select(n => n.Substring(4));
Doing Replace instead of Substring might replace several substrings in one name (and is slower even if it doesn't do so).
I would not recommend relying on the position of the numeric value or the length of the string or the fact that the text reads 'name' at all. Instead you can use a simple regular expression to extract it consistently:
Regex regex = new Regex(#"[0-9]+");
var numbers = ConfigurationManager.AppSettings
.AllKeys.Select(p => regex.Match(p).Value).ToArray();

without for loop how can is show var type these value in TextBox

I have a scenario where i have a
var testVar= list1.Intersect(list2);
testVar contains about 400 values.
Now i have to show all the value in the text box.
Like:
Textbox1.text = testVar...
So, without for loop how can is show these value in TextBox
Please, Help
How about something like this:
string myText = String.Join(",", (from my in myList
select my.ToString()).ToArray());
You might want to replace 'my.ToString()' with whatever makes the most sense given your object's type (or, if they are already strings, just select 'my')
Assuming you are working with Lists of strings, you want to do this:
Textbox1.Text = String.Join(", ", testVar.Select(s => s).ToArray());
The reason I left the s => s lambda is that your list might not be of strings. So this construct will give you a chance to build your string items accordingly.
I am NOT saying this is the good way because I use the String.Join solution presented earlier BUT, for the sake of completeness and because I know most of us like to see how other people solve problems, a solution I've seen used is the Linq Aggregate() function.
Dim laNumbers() As String = {"one", "two", "three"}
Dim lsCSV = laNumbers.Aggregate(Function(s1, s2) s1 & ", " & s2)
Console.WriteLine(lsCSV)

Categories