简体   繁体   English

LINQ 条件选择和格式化

[英]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 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:在这种情况下,我试图隔离并仅计算数字 5 的出现次数,因此我的输出应为:

agd69dnbd 3 bdggjykbcx 6 bbb 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.我当前的代码如下,其中 GroupAdjacentBy 是一个函数,用于对字符出现次数进行分组和计数,如上所述。

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.正则表达式是比 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.不确定您是打算每 5 个字符替换一次,还是仅在有多个相邻的 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. Johnathan Barclay 已经给出了最好的答案。 But just for the case that you need something similar by using Linq and to show an alternative solution:但仅在您需要使用 Linq 进行类似操作并显示替代解决方案的情况下:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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