简体   繁体   中英

LINQ conditional selection and formatting

I have a string of characters and I'm trying to set up a query that'll substitute a specific sequence of similar characters into a character count. Here's an example of what I'm trying to do:

agd69dnbd 555 bdggjykbcx 555555 bbb

In this case, I'm trying to isolate and count ONLY the occurrences of the number 5, so my output should read:

agd69dnbd 3 bdggjykbcx 6 bbb

My current code is the following, where GroupAdjacentBy is a function that groups and counts the character occurrences as above.

var res = text
.GroupAdjacentBy((l, r) => l == r)
.Select(x => new { n = x.First(), c = x.Count()})
.ToArray();

The problem is that the above function groups and counts EVERY SINGLE character in my string, not the just the one character I'm after. Is there a way to conditionally perform that operation on ONLY the character I need counted?

Regex is a better tool for this job than LINQ.

Have a look at this:

string input = "agd69dnbd555bdggjykbcx555555bbb";

string pattern = @"5+"; // Match 1 or more adjacent 5 character

string output = Regex.Replace(input, pattern, match => match.Length.ToString());

// output = agd69dnbd3bdggjykbcx6bbb

Not sure if your intending to replace every 5 character, or just when there is more than one adjacent 5.

If it's the latter, just change your pattern to:

string pattern = @"5{2,}"; // Match 2 or more adjacent 5's

The best answer was already given by Johnathan Barclay. But just for the case that you need something similar by using Linq and to show an alternative solution:

var charToCombine = '5';
var res = text
    .GroupAdjacentBy((l, r) => l == r )
    .SelectMany(x => x.Count() > 1 && x.First() == charToCombine ? x.Count().ToString() : x)
    .ToArray();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM