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>());
}
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
I have a "Panel" model that has multiple "Panel Pages". I would like to get a list of all panels, and fill each panel with its respective "Panel Pages".
Here is my code currently (that works):
public IEnumerable<DynamicCustomPanel> GetCustomPanels()
{
var customPanels = _customPanelService.GetDynamicCustomPanels();
var dynamicCustomPanels = customPanels.ToList();
foreach (var customPanel in dynamicCustomPanels.ToList())
{
var customPanelPages = _customPanelPageService.GetCustomPanelPages(customPanel.PanelGUID.ToString());
customPanel.CustomPanelPages = customPanelPages;
}
return dynamicCustomPanels;
}
How do I do this in an minimal amount of lines?
This should work:
public IEnumerable<DynamicCustomPanel> GetCustomPanels()
{
return _customPanelService.GetDynamicCustomPanels().Select(p => {
p.CustomPanelPages = _customPanelPageService.GetCustomPanelPages(p.PanelGUID.ToString());
return p;
});
}
That's technically 3 statements (two returns and an assignment) and one block, though it's kind of an abuse of the Select() method. I might write it like this instead:
public IEnumerable<DynamicCustomPanel> GetCustomPanels()
{
foreach(var p in _customPanelService.GetDynamicCustomPanels())
{
p.CustomPanelPages = _customPanelPageService.GetCustomPanelPages(p.PanelGUID.ToString());
yield return p;
}
}
Which is... also 3 statements (counting foreach) and one block, just spaced different to use one more line of text.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I have an list of string values which looks like this:
GREEN,BLUE,BLUE
BLUE,BLUE,GREEN
GREEN,RED,RED
RED,BLUE,BLUE
BLUE,RED,RED
GREEN,BLUE,BLUE
RED,GREEN,BLUE
I will use a foreach to loop through each line and find unique values.
I need a regex that returns true is there are no color duplicates (RED,GREEN,BLUE) and false if there are color duplicates (RED,GREEN,RED).
What would the regex look like?
You can try using Linq instead of regular expressions:
using System.Linq;
...
string source = "BLUE,BLUE,GREEN";
// do we have three distinct items?
bool allDistinct = source.Split(',').Distinct().Count() >= 3;
Test:
List<string> list = new List<string>() {
"GREEN,BLUE,BLUE",
"BLUE,BLUE,GREEN",
"GREEN,RED,RED",
"RED,BLUE,BLUE",
"BLUE,RED,RED",
"GREEN,BLUE,BLUE",
"RED,GREEN,BLUE",
};
var result = list
.Select(source => $"{source,-15} {source.Split(',').Distinct().Count() >= 3}");
Console.Write(string.Join(Environment.NewLine, result));
Outcome:
GREEN,BLUE,BLUE False
BLUE,BLUE,GREEN False
GREEN,RED,RED False
RED,BLUE,BLUE False
BLUE,RED,RED False
GREEN,BLUE,BLUE False
RED,GREEN,BLUE True
Edit: Linq can help out in the generalized case:
bool allDistinct = !source
.Split(',')
.GroupBy(item => item, (k, s) => s.Skip(1).Any())
.Any(item => item);
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 8 years ago.
Improve this question
StringBuilder sbOccupation = new StringBuilder();
foreach (ListItem li in cblOccupation.Items)
{
if (li.Selected)
{
sbOccupation.Append(li.Text);
sbOccupation.Append(",");
}
}
property.Occupation=sbOccupation.ToString().Remove(sbOccupation.ToString().LastIndexOf(","), 1);
If no checkboxes are checked, then
li.Selected is false for each
li in cblOccupation.Items, and then
.LastIndexOf(","), 1) produces the error since
sbOccupation.Append(",");
never happened.
If nothing has been appended to sbOccuption, then it will be empty - so LastIndexOf(',') will return -1, which isn't a valid first argument to string.Remove.
Given that you know it will always be the last character of the result, you could just use:
if (sbOccuptation.Length > 0)
{
// Trim the trailing comma
sbOccupation--;
}
string text = sbOccupation.ToString();
However, it would be simpler just to use string.Join and LINQ:
// This replaces *all* your code
property.Occupation = string.Join(",", cblOccuptation.Items
.Cast<ListItem>()
.Where(li => li.Selected)
.Select(li => li.Text));
If you're using .NET 3.5, you'll need a call to ToArray after the Select call, but that's simple enough.
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"];
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 9 years ago.
Improve this question
How apply linq select to string array in C#
ex :
string[] result;
...
result.Select(..)
?
Thanks.
You pass in a lambda function that tells the system what you want to do with each string.
string[] result;
...
var newList = result.Select(s => {do something with s});
The function can do most anything that takes a string as an input and returns a value - it doesn't even have to return a string! For example, if the strings contained numeric characters, you could return a collection of numbers:
IEnumerable<int> newList = result.Select(s => int.Parse(s));
Note that the original array will not be changed.