Say I have this array of strings:
假设我有这个字符串数组:
string[] arrayToParse = {2, G, R, G, B};
I need to parse through the array to check how many times is a string present so that I may end up with values like this:
我需要解析数组以检查字符串存在多少次,这样我最终可能得到如下值:
2
GG
R
B
So each time the loop detects if there's another string identical, he "concatenates", then add the value to a list.
因此,每次循环检测到是否有另一个字符串相同时,他“连接”,然后将值添加到列表中。
If I take another example: string[] arrayToParse2 = {2, Q, T, T, U, U}
Should end up with these values:
如果我采取另一个例子:string [] arrayToParse2 = {2,Q,T,T,U,U}应该以这些值结束:
2
Q
TT
UU
Any help anyone?
有人帮忙吗?
3 个解决方案
#1
6
Use LINQ (GroupBy
method) and string.Join
:
使用LINQ(GroupBy方法)和string.Join:
string[] arrayToParse = {"2", "G", "R", "G", "B"};
string[] results = arrayToParse.GroupBy(x => x)
.Select(g => string.Join(string.Empty, g))
.ToArray();
Works for both your sample inputs.
适用于您的样本输入。
#2
2
You can use Linq:
你可以使用Linq:
var stringGroups = arrayToParse.GroupBy(str => str);
Now you can display these groups with String.Join
:
现在,您可以使用String.Join显示这些组:
foreach(var group in stringGroups)
Console.WriteLine(string.Join("", group));
#3
1
I would go with the LINQ approach. If it is not available or you don't want to use it, here is a longuer version (easier to understand if you've never used LINQ).
我会选择LINQ方法。如果它不可用或您不想使用它,这里是一个longuer版本(如果您从未使用过LINQ,则更容易理解)。
string[] arrayToParse = {2, G, R, G, B};
List<String> parsedList = new List<String>
foreach(String sToParse in arrayToParse)
{
if (parsedList.Count <= 0)
parsedList.Add(sToParse);
else
foreach(String sInParsedList in parsedList)
{
if(sToParse == sInParsedList)
sInParsedList += sToParse;
else
parsedList.Add(sToParse);
}
string[] parsedArray = parsedList.ToArray();
#1
6
Use LINQ (GroupBy
method) and string.Join
:
使用LINQ(GroupBy方法)和string.Join:
string[] arrayToParse = {"2", "G", "R", "G", "B"};
string[] results = arrayToParse.GroupBy(x => x)
.Select(g => string.Join(string.Empty, g))
.ToArray();
Works for both your sample inputs.
适用于您的样本输入。
#2
2
You can use Linq:
你可以使用Linq:
var stringGroups = arrayToParse.GroupBy(str => str);
Now you can display these groups with String.Join
:
现在,您可以使用String.Join显示这些组:
foreach(var group in stringGroups)
Console.WriteLine(string.Join("", group));
#3
1
I would go with the LINQ approach. If it is not available or you don't want to use it, here is a longuer version (easier to understand if you've never used LINQ).
我会选择LINQ方法。如果它不可用或您不想使用它,这里是一个longuer版本(如果您从未使用过LINQ,则更容易理解)。
string[] arrayToParse = {2, G, R, G, B};
List<String> parsedList = new List<String>
foreach(String sToParse in arrayToParse)
{
if (parsedList.Count <= 0)
parsedList.Add(sToParse);
else
foreach(String sInParsedList in parsedList)
{
if(sToParse == sInParsedList)
sInParsedList += sToParse;
else
parsedList.Add(sToParse);
}
string[] parsedArray = parsedList.ToArray();