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);
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 2 years ago.
Improve this question
I have a string array as follows:
string[] stringArray = { "1122|false", "1123|true", "1124|true", "1125|false" };
In essence, it is broken down by id|active where for example id is say 1122 and active is true or false.
Say my id was 1123, how would I search this array to get the value of true in this case? I understand Substring needs to be used with IndexOf but not sure how to tie it together.
Little bit of LINQ and String.Split should do the trick.
string[] stringArray = { "1122|false", "1123|true", "1124|true", "1125|false" };
int id = 1123;
var itemWithGivenId = stringArray
.SingleOrDefault(s => int.Parse(s.Split('|')[0]) == id);
Console.WriteLine(bool.Parse(itemWithGivenId.Split('|')[1]));
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 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 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.