As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I have a dictionary
Dictionary<string, List<string>> dictGenSubs = new Dictionary<string, List<string>>();
How can I make sure that there is no whitespace in any of the records of the dictionary?
I assume you are talking only about the strings in the list.
To achieve that goal, you can use this code:
dictGenSubs = dictGenSubs.ToDictionary(
x => x.Key,
x => x.Value
.Select(x => x.Replace(" ", string.Empty))
.ToList());
This creates a new dictionary with new lists as the values of the dictionary. Each string in each list will be adjusted before being added to the new list.
A more efficient approach would be to update the existing dictionary and the existing lists:
foreach(var list in dictGenSubs.Values)
{
for(int i = 0; i < list.Count; ++i)
list[i] = list[i].Replace(" ", string.Empty);
}
Do you mean any whitespace at all in any of the strings in each value? Here's a succinctly inefficient way with LINQ:
bool hasWhitespace = dictGenSubs.SelectMany(kv => kv.Value)
.Any(s => s.Any(char.IsWhiteSpace));
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I need to do a LINQ expression where the expression varies on how deep the expected node is in the hierarchy.
So I use concat on a string like this:
var parString = string.Concat(Enumerable.Repeat(".SelectMany(f => f.level)", level));
so if its 4 levels deep I get the string :
string1 = ".SelectMany(f => f.level).SelectMany(f => f.level).SelectMany(f => f.level).SelectMany(f => f.level)"
I then want to use this string in a LINQ expression, example:
List + string1 + .FirstOrDefault(.......);
Is this even possible? How can I do it?
Use a for loop to determine how many times to call .SelectMany:
var query = List;
for(int depth = 4; depth > 0; depth--)
{
query = query.SelectMany(f => f.level);
}
// Materialize query with `FirstOrDefault` or anything you need
Notice that currently if you reach the maximum depth and still continue you will get an exception. To solve that you can add an if statement to check that f.level is not null or not empty depending on your logic. Something like:
for(int depth = 4; depth > 0; depth--)
{
query = query.SelectMany(f => f.level ?? Enumerable.Empty<YourType>());
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
The question is on C#.
I have a string "value1=1234;value2=2345;value3=3456;value4= ..."
What is the best way to retrieve the values?
I thought about String.Split(";") but I don't know how to retrieve the values only. The result I get includes the prefix I don't want.
I only want the values of "1234", "2345", "3456"... nothing else, and them put them into a list of strings.
How do I solve this? Thanks.
If the format is always fixed, you can do it fairly easily via LINQ:
List<string> values = theString.Split(';').Select(s => s.Split('=')[1]).ToList();
Note that you may want to use RemoveEmptyEntries if your input string ends in a semi-colon:
List<string> values = theString
.Split(new[]{';'}, StringSplitOptions.RemoveEmptyEntries)
.Select(s => s.Split('=')[1]).ToList();
This would prevent an exception from occuring within the Select. If the input doesn't end in a semi-colon, however, this wouldn't be necessary.
var text = "value1=1234;value2=2345;value3=3456;value4= ...";
var pieces = text.Split('=');
var values = new Dictionary<string,string>();
for(int index = 0; index < pieces.Length; index += 2)
{
values.Add(pieces[index], pieces[index + 1]);
}
This will give you a dictionary of the pairs where the key is the left-hand side of the '=' and the value is the string representation of the value, which allows your to do:
var value1 = values["value1"];
var value2 = values["value2"];
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
I was reading an old post from coding horror (http://www.codinghorror.com/blog/2007/02/why-cant-programmers-program.html) It's still a very entertaining read, you'll notice a lot of the people providing answers actually made small logical errors themselves (about 30% of them).
Anyway, thought I'll set myself a small challenge and found a bunch of fizzbuzz questions here: Alternate FizzBuzz Questions
"Reverse a String" - with all the built-in methods in the .net framework there are many ways to do this.
My question is:
1. how do you reverse a string using LINQ?
2. can you come up with other interesting ways of reversing a string in C#?
Here's are two examples I came up with
1. completely from scratch
2. using enumerable's reverse methods (1 liner)
private static string FromScratchSimplified(string input)
{
// constructed reversed char array
char[] reversedCharArray = new char[input.Length];
for (int i = 0; i < input.Length; i++)
{
reversedCharArray[i] = input[input.Length-1-i];
}
// build string from char array
string reversedString = new String(reversedCharArray);
return reversedString;
}
private static string UsingEnumerableReverseMethod(string input)
{
// using Enumerable.Reverse method
return new String(input.Reverse().ToArray());
}
Any more?
new string(Enumerable.Range(1, input.Length).Select(i => input[input.Length - i]).ToArray())
To keep it as close to query syntax as possible:
given:
string aString = "please reverse me";
then:
var reversed = new string((from c in aString.Select((value, index) => new { value, index })
orderby c.index descending
select c.value).ToArray());
Console.WriteLine(reversed);
yields:
em esrever esaelp
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I want to convert ILIST<string> to ILIST <object>
How can achieve this using C#?
var oList = (IList<object>)sList.Cast<object>().ToList();
IList<string> s = new List<string>() ;
IList<object> o = new List<object>();
foreach (string x in o)
s.Add(x);
The following should do it:
IList<String> strings = new List<String> { "a", "b", };
IList<Object> objects = strings.Cast<Object>().ToList();
You can test the results in LinqPad by calling: objects.Dump();
stringList.Select(x => (object)x).ToList();
that is what the Lambda expressions are for.
you can use a simple Lambda expression for the conversion. Provided you are on .NET 2.0 or above.
eg:
stringList.Select(x => (object)x).ToList();
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
There are some cool and exciting features in .NET 3.5/C# 3.0, and with those features comes some darn interesting ways to write the exact same line of code.
Using the above stated tool set (and by extension .NET 2.0 stuff), what are the different ways the below code snippet could reasonably be rewritten?
string uploadDirectory = "c:\\some\\path\\";
if (Directory.Exists(uploadDirectory)) {
string[] files = Directory.GetFiles(uploadDirectory);
foreach (string filename in files) {
if (File.GetLastWriteTime(filename).AddHours(12) < DateTime.Now) {
File.Delete(filename);
}
}
}
Lambda:
if (Directory.Exists(uploadDirectory))
Directory.GetFiles(uploadDirectory)
.Where(f => File.GetLastWriteTime(file) < DateTime.Now.AddHours(-12))
.Each(f => File.Delete(f));
Edit: On 2nd thought, you can avoid the security lookups on each File access by using DirectoryInfo and FileInfo instead of the static File methods:
var di = new DirectoryInfo(uploadDirectory);
if (di.Exists()) {
di.GetFiles()
.Where(f => f.LastWriteTime < DateTime.Now.AddHours(-12))
.Each(f=> f.Delete());
}
And for those missing their own Each method:
void Each<T>(this IEnumerable e, Action<T> action) {
foreach (T t in e) {
action(t);
}
}
To make this really crazy, and fit the C# 3.0 theme, let's throw in an anonymous type:
di.GetFiles().Select(f => new() {
Delete = f.LastWriteTime < DateTime.Now.AddHours(-12) ? f.Delete : () => { }
}).Delete();
But that just doesn't make any sense. ;)
Well, the first bit maps quite neatly to a LINQ query... but there is (deliberately) no ForEach in regular LINQ. We can annoy Eric and add one, though ;-p
So the following uses LINQ and a custom extension method - but we could re-write the exact same code (i.e. the same IL) as:
query syntax (as below)
fluent syntax (.Where().Select() ec)
explicit static (Enumerable.Where(...))
lambdas vs anonymous methods vs named methods (last changes the IL)
delegates with/without the abbreviated (C# 2.0) delegate "new" syntax
generic calls with/without generic type inference (Where() vs Where<T>())
call to File.Delete vs call to x=>File.Delete(x) etc
etc
static void Main()
{
string uploadDirectory = "c:\\some\\path\\";
if (Directory.Exists(uploadDirectory))
{
var files = from filename in Directory.GetFiles(uploadDirectory)
where File.GetLastWriteTime(filename) < DateTime.Now.AddHours(-12)
select filename;
files.ForEach(File.Delete);
}
}
static void ForEach<T>(this IEnumerable<T> items, Action<T> action)
{
foreach (T item in items)
{
action(item);
}
}
We could write the DateTime code with a custom Expression, but that would be overkill...
However, I doubt we could ever run out of ways of writing it ;-p