c# Copying jagged arrays to strings - c#

My function is supposed to split a string by "&" ";" and "," and return a triple jagged array and vice versa. (From data like: 1,2,3;4,5,6&1,2,3;4,5,6)
I've been struggling hard to make it work, now for some reason I'm getting a system.argumentnullexception on
Array.Copy(playerOneEnts, allEnts[0], playerOneEnts.Length);
Array.Copy(playerTwoEnts, allEnts[1], playerTwoEnts.Length);
Full code:
public string convertToString(string[][][] allEnts)
{
string Player = string.Empty;
string[][] playerOneEnts = new string[maxEnts][];
string[][] playerTwoEnts = new string[maxEnts][];
Array.Copy(allEnts[0], playerOneEnts, allEnts[0].Length);
Array.Copy(allEnts[1], playerTwoEnts, allEnts[1].Length);
for (int j = 0; j < playerOneEnts.Length; j++)
{
for (int i = 0; i < playerOneEnts[j].Length; i++)
{
Player += playerOneEnts[j][i] + ",";
}
Player = Player.TrimEnd(',');
Player += ";";
}
Player = Player.TrimEnd(';');
Player += "&";
for (int j = 0; j < playerTwoEnts.Length; j++)
{
for (int i = 0; i < playerTwoEnts[j].Length; i++)
{
Player += playerTwoEnts[j][i] + ",";
}
Player = Player.TrimEnd(',');
Player += ";";
}
Player = Player.TrimEnd(';');
return Player;
}
public string[][][] convertToArray(string ents)
{
string[] p = new string[2];
string[][] playerOneEnts = new string[maxEnts][];
string[][] playerTwoEnts = new string[maxEnts][];
string[][][] allEnts = new string[2][][];
p = ents.Split('&');
try
{
playerOneEnts = p[0].Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries).Select(chunk => chunk.Split(',')).ToArray();
playerTwoEnts = p[1].Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries).Select(chunk => chunk.Split(',')).ToArray();
MessageBox.Show(playerOneEnts.Length.ToString());
Array.Copy(playerOneEnts, allEnts[0], playerOneEnts.Length);
Array.Copy(playerTwoEnts, allEnts[1], playerTwoEnts.Length);
}
catch
{
MessageBox.Show("unable to convert string", "Fatal Error");
}
return allEnts;
}
The code looks like a disaster to me, if anyone knows a nicer way to convert this to a string I'd be happy for any ideas. Getting rid of my Error would help me enough already.
Thanks!

Here is example using Linq (requires .Net 4.0):
var source = "1,2,3;4,5,6&1,2,3;4,5,6";
string[][][] decoded = source.Split('&').Select(x => x.Split(';').Select(y => y.Split(',').ToArray()).ToArray()).ToArray();
string reencoded = String.Join("&", decoded.Select(x => String.Join(";", x.Select(y => String.Join(",", y)))));
Alternatively IEnumarable generics can be used to avoid conversion to arrays.
Warning: This code doesn't validates input e.g. array lengths.
Edit: Re-encoder for .NET 3.5:
var reencoded = String.Join("&", decoded.Select(x => String.Join(";", x.Select(y => String.Join(",", y)).ToArray())).ToArray());

You can do it using nested for-loops like this:
string p = "1,2,3;4,5,6&1,5,3;4,5,9";
List<List<List<string>>> result = new List<List<List<string>>>();
foreach (var a in p.Split('&'))
{
List<List<string>> level2 = new List<List<string>>();
foreach (var b in a.Split(';'))
{
level2.Add(new List<string>(b.Split(',')));
}
result.Add(level2);
}
var x = result[0][1][2]; // This will result in '6'.
The encoding is similar:
string encoded;
List<string> dec1 = new List<string>();
foreach (var a in result)
{
string e = "";
List<string> z = new List<string>();
foreach (var b in a)
{
z.Add(String.Join(",", b));
}
e = String.Join(";", z);
dec1.Add(e);
}
encoded = String.Join("&", dec1);

Related

C# Variable not getting all values outside for loop

I have two values in the dictionary but when I try to get the two values outside the loop I am only getting one value. The locationdesc variable value are being overwritten. Is there a better way to create unique variables to handle this issues
There are two keys location-1 and location-2. I am trying to figure out how to get both the values outside the loop. Am I doing it wrong?
string locationDesc = "";
string locationAddress = "";
int count = dictionary.Count(D => D.Key.StartsWith("location-"));
for (int i = 1; i <= count; i++)
{
if (dictionary.ContainsKey("location-"+i))
{
string locationData = dictionary["location-"+i];
string[] locationDataRow = locationData.Split(':');
locationDesc = locationDataRow[0];
locationAddress = locationDataRow[1];
}
}
// Only getting location-2 value outside this loop since locationDesc is not unique.
Debug.WriteLine("Location Desc from dictionary is : " + locationDesc);
Debug.WriteLine("Location Add from dictionary is : " + locationAddress);
What I would like to get here is get both the values like locationDesc1 and locationDesc2 instead of locationDesc
What I am looking for is to create locationDesc and locationAddress unique so I can access both the values outside the for loop.
More Explanation as I was not very clear:
I have a dynamic table that will be created in the front end. Every time a location is created I create a cookie. For e.g. location-1, location-2 ...location-n with the location description and location values as values in the cookie. I am trying to access these values in the backend by creating a dictionary so I can assign all the values to unique variable which will make it easier for me to pass these values to a api call. I think I am over complicating a simple issue and might be doing it wrong.
My api call will be something like this:
<field="" path="" value=locationDesc1>
<field="" path="" value=locationDesc2>
The problem with your loop is that you are relying on the position of the entry in the dictionary matching the index within your loop. Your first line of code pretty much has it though:
int count = dictionary.Count(D => D.Key.StartsWith("location-"));
What this tells me is that you are looking for all entries in your dictionary where the key starts with "location-". So why not do that directly:
var values = dictionary.Where(d => d.Key.StartsWith("location-"));
And to do the extraction/string splitting at the same time:
var values = dictionary
.Where(d => d.Key.StartsWith("location-"))
.Select(d => d.Item.Split(':')
.Select(s => new
{
LocationDesc = s[0],
LocationAddress = s[1]
});
This will give you an IEnumerable of LocationDesc/LocationAddress pairs which you can loop over:
foreach(var pair in values)
{
Debug.WriteLine(pair.LocationDesc);
Debug.WriteLine(pair.LocationAddress);
}
Try this:
int count = dictionary.Count(D => D.Key.StartsWith("location-"));
Dictionary<string, string> values = new Dictionary<string, string>();
for (int i = 1; i <= count; i++)
{
if (dictionary.ContainsKey("location-"+i))
{
string locationData = dictionary["location-"+i];
string[] locationDataRow = locationData.Split(':');
values.Add(locationDataRow[0],locationDataRow[1]);
}
}
foreach (var item in values)
{
Debug.WriteLine(item.Key + " : " + item.Value);
}
As you are dealing with multiple values, you should go with a container where you can store all the values.
if you are dealing with only two unique values then use below code.
int count = dictionary.Count(D => D.Key.StartsWith("location-"));
string[] locationDesc = new string[2];
string[] locationAddress = new string[2];
for (int i = 1; i <= count; i++)
{
if (dictionary.ContainsKey("location-"+i))
{
string locationData = dictionary["location-"+i];
string[] locationDataRow = locationData.Split(':');
locationDesc[i-1] = locationDataRow[0];
locationAddress[i-1] = locationDataRow[1];
}
}
for (int i = 0; i <= locationDesc.Length-1; i++)
{
Debug.WriteLine("Location Desc from dictionary is : " + locationDesc[i]);
Debug.WriteLine("Location Add from dictionary is : " + locationAddress[i]);
}
if number of unique values is not fixed then go with ArrayList
int count = dictionary.Count(D => D.Key.StartsWith("location-"));
ArrayList locationDesc = new ArrayList();
ArrayList locationAddress = new ArrayList();
for (int i = 1; i <= count; i++)
{
if (dictionary.ContainsKey("location-"+i))
{
string locationData = dictionary["location-"+i];
string[] locationDataRow = locationData.Split(':');
locationDesc.Add(locationDataRow[0]);
locationAddress.Add(locationDataRow[1]);
}
}
for (int i = 0; i < locationDesc.Count; i++)
{
Debug.WriteLine("Location Desc from dictionary is : " + locationDesc[i]);
Debug.WriteLine("Location Add from dictionary is : " + locationAddress[i]);
}
Simple One. If you only want to show result using Debug.WriteLine, then go with below code
int count = dictionary.Count(D => D.Key.StartsWith("location-"));
for (int i = 1; i <= count; i++)
{
if (dictionary.ContainsKey("location-"+i))
{
string locationData = dictionary["location-"+i];
string[] locationDataRow = locationData.Split(':');
Debug.WriteLine("Location Desc from dictionary is : " + locationDataRow[0]);
Debug.WriteLine("Location Add from dictionary is : " + locationDataRow[1]);
}
}
Not able to prepare Code in Visual Studio at the moment therefore there may be some syntax errors.
It is hard to judge what you are event trying to do. I would not just be dumping objects you already have into other objects for fun. If you are just trying to expose values in a loop for use with another function, you can just use LINQ to iterate over the dictionary. If you want a specific value just add a where LINQ expression. LINQ should be in any .NET framework after 3.5 I believe.
public static void ApiMock(string s)
{
Console.WriteLine($"I worked on {s}!");
}
static void Main(string[] args)
{
var d = new Dictionary<int, string> {
{ 1, "location-1" },
{ 2, "location-2" },
{ 3, "location-3" }
};
d.ToList().ForEach(x => ApiMock(x.Value));
//I just want the second one
d.Where(x => x.Value.Contains("-2")).ToList().ForEach(x => ApiMock(x.Value));
//Do you want a concatenated string
var holder = string.Empty;
d.ToList().ForEach(x => holder += x.Value + ", ");
holder = holder.Substring(0, holder.Length - 2);
Console.WriteLine(holder);
}

Searching for a string in a string

Dear stackoverflow members,
I have this string:
string data = "1Position1234Article4321Quantity2Position4323Article3323Quantity";
I want to search for the values where the "keyword" is Position. In this case I want to get back 1 and 2. Each value is "indexed" with its own "keyword". So the value 1 in this string has the Position seperator. The value 1234 has the Article seperator and the value 4321 has the Quantity seperator.
I need a way to search through the string and want to get all positions, articles and quantitys back. Without the keywords.
Output shout be:
string[] position = {"1", "2"};
string[] article = {"1234", "4323"};
string[] quantity = {"4321", "3323"};
Hopefully some can help me here.
Thanks!
This is q quick solution I've come up with in LinqPad:
void Main()
{
string data = "1Position1234Article4321Quantity2Position4323Article3323Quantity";
var Articles = Indices(data, "Article").Dump("Articles: ");
var Posistions = Indices(data, "Position").Dump("Positions :");
var Quantities = Indices(data, "Quantity").Dump("Quantities :");
}
// Define other methods and classes here
public List<int> Indices(string source, string keyword)
{
var results = new List<int>();
//source: http://stackoverflow.com/questions/3720012/regular-expression-to-split-string-and-number
var temp = Regex.Split(source, "(?<Alpha>[a-zA-Z]*)(?<Numeric>[0-9]*)").ToList().Where (r => !String.IsNullOrEmpty(r)).ToList();
//select the list with index only where key word matches
var indices = temp.Select ((v,i) => new {index = i, value = v})
.Where (t => t.value == keyword);
foreach (var element in indices)
{
int val;
//get previous list entry based on index and parse it
if(Int32.TryParse(temp[element.index -1], out val))
{
results.Add(val);
}
}
return results;
}
Output:
Here's a possible algorithm:
Run trough the list and take each number / keyword.
Put them in a dictionary with key "keyword", value a list with all "numbers".
Iterate the dictionary and print they key + its values.
Below snippet can use to get the output like what you expected.
string data = "1Position1234Article4321Quantity2Position4323Article3323Quantity";
StringBuilder sb = new StringBuilder();
StringBuilder sbWord = new StringBuilder();
bool isDigit = false;
bool isChar = false;
Dictionary<int, string> dic = new Dictionary<int, string>();
int index = 0;
for (int i = 0; i < data.Length; i++)
{
if (char.IsNumber(data[i]))
{
isDigit = true;
if (isChar)
{
dic.Add(index, sb.ToString() + "|" + sbWord.ToString());
index++;
isChar = false;
sb.Remove(0, sb.Length);
sbWord.Remove(0, sbWord.Length);
}
}
else
{
isDigit = false;
isChar = true;
sbWord.Append(data[i]);
}
if (isDigit)
sb.Append(data[i]);
if (i == data.Length - 1)
{
dic.Add(index, sb.ToString() + "|" + sbWord.ToString());
}
}
List<string> Position = new List<string>();
List<string> Article = new List<string>();
List<string> Quantity = new List<string>();
if (dic.Count > 0)
{
for (int i = 0; i < dic.Count; i++)
{
if (dic[i].Split('|')[1] == "Position")
Position.Add(dic[i].Split('|')[0]);
else if (dic[i].Split('|')[1] == "Article")
Article.Add(dic[i].Split('|')[0]);
else
Quantity.Add(dic[i].Split('|')[0]);
}
}
string[] Position_array = Position.ToArray();
string[] Article_array = Article.ToArray();
string[] Quantity_array = Quantity.ToArray();
Try this simple solution.
class StrSplit{
public static void main(String args[]){
int i;
String str = "1Position1234Article4321Quantity2Position4323Article3323Quantity";
String pattern= "(?<=Position)|(?<=Article)|(?<=Quantity)";
String[] parts = str.split(pattern);
List<String> Position = new ArrayList<String>();
List<String> Article = new ArrayList<String>();
List<String> Quantity = new ArrayList<String>();
for( i=0;i<parts.length;i++)
{
pattern="Position";
String[] subParts;
if(parts[i].contains(pattern))
{
subParts = parts[i].split(pattern);
Position.add(subParts[0]);
}
pattern="Article";
if(parts[i].contains(pattern))
{
subParts = parts[i].split(pattern);
Article.add(subParts[0]);
}
pattern="Quantity";
if(parts[i].contains(pattern))
{
subParts = parts[i].split(pattern);
Quantity.add(subParts[0]);
}
}
System.out.println("Position:");
for(i = 0; i < Position.size(); i++) {
System.out.println(Position.get(i));
}
System.out.println("Article:");
for(i = 0; i < Article.size(); i++) {
System.out.println(Article.get(i));
}
System.out.println("Quantity:");
for(i = 0; i < Quantity.size(); i++) {
System.out.println(Quantity.get(i));
}
}
}
Output:
Position:
1
2
Article:
1234
4323
Quantity:
4321
3323

Decrypt string to number value

I have my code to decrypt the string to numbers but i have the result
every time "-1-1-1"
protected void submit_Click(object sender, EventArgs e)
{
decryptScore(txtscore.Text);
}
public string decryptScore(string s)
{
string[] firstDigitArray = { "f85au", "kt50e", "cmt5s", "v5072", "fc5i3", "56f7l", "7gj81", "yn90y", "5o3ko", "ntakn" };
string[] secondDigitArray = { "hkym6", "xj97c", "54v6q", "nawf9", "9e1gp", "9gww9", "5oj5p", "0ba5t", "yizld", "bt064" };
string[] thirdDigitArray = { "uku91", "rn2k4", "uuq78", "nkurt", "8kxqs", "9p7kc", "hd8x6", "57b6o", "7iucu", "do6bq" };
string[] fourthDigitArray = { "0hdro", "0wqrc", "wa5ny", "857mg", "3f7ro", "kerph", "0mhw1", "tpb8f", "8rho3", "4hc11" };
string[][] digitsArray = {firstDigitArray, secondDigitArray, thirdDigitArray, fourthDigitArray};
string decryptedScore = "";
int scorelength = s.Length / 5;
for (int i = 0; i < scorelength; i++)
{
string d = s.Substring(i * 5, 5);
decryptedScore += (digitsArray[i][i].IndexOf(d));
}
score.Text = decryptedScore;
return decryptedScore;
}
public string decryptScore(string s)
{
var firstDigitArray = new List<string>{ "f85au", "kt50e", "cmt5s", "v5072", "fc5i3", "56f7l", "7gj81", "yn90y", "5o3ko", "ntakn" };
var secondDigitArray = new List<string> { "hkym6", "xj97c", "54v6q", "nawf9", "9e1gp", "9gww9", "5oj5p", "0ba5t", "yizld", "bt064" };
var thirdDigitArray = new List<string> { "uku91", "rn2k4", "uuq78", "nkurt", "8kxqs", "9p7kc", "hd8x6", "57b6o", "7iucu", "do6bq" };
var fourthDigitArray = new List<string> { "0hdro", "0wqrc", "wa5ny", "857mg", "3f7ro", "kerph", "0mhw1", "tpb8f", "8rho3", "4hc11" };
var digitsArray = new List<List<string>>{ firstDigitArray, secondDigitArray, thirdDigitArray, fourthDigitArray };
string decryptedScore = "";
int scorelength = s.Length / 5;
for (int i = 0; i < scorelength; i++)
{
string d = s.Substring(i * 5, 5);
decryptedScore += (digitsArray[i].FindIndex(x=>x==d));
}
return decryptedScore;
}
PS: Don't forget if scorelength is greater or equal to 4 you'll get an exception(since you only have 4 digitArrays)
In the line
decryptedScore += (digitsArray[i][i].IndexOf(d));
you are searching for a string a single string for a the value. You need to search the array.
Change this line to
decryptedScore += Array.IndexOf(digitsArray[i], d);
This will search the array for a particular value and return you it's index. As a result you will get the required number back.
Replace
decryptedScore += (digitsArray[i][i].IndexOf(d));
with
decryptedScore += Array.IndexOf(digitsArray[i], d);

How to convert a list with splitted strings to a possible value sets?

I need to implement a module which will convert a List which with splitted string values to a possible value sets.
For Example
consider the list contains following values
1
1,2
3
4
5
The module should convert the above list to list of possible value sets
1,2,3,4,5
1,1,3,4,5
thanks in advance
This will do it, although it will return your example in the opposite order:
static IEnumerable<string> Permutations(
IEnumerable<string> input,
char separator)
{
var sepAsString = separator.ToString();
var enumerators = input
.Select(s => s.Split(separator).GetEnumerator())
.ToArray();
if (!enumerators.All(e => e.MoveNext())) yield break;
while (true)
{
yield return String.Join(sepAsString, enumerators.Select(e => e.Current));
if (enumerators.Reverse().All(e => {
bool finished = !e.MoveNext();
if (finished)
{
e.Reset();
e.MoveNext();
}
return finished;
}))
yield break;
}
}
Usage:
var list = new[] { "1", "1,2", "3", "4", "5" }.ToList();
var perms = Permutations(list, ',').ToList();
Rawling's answer is pretty solid, but i don't find it easy to read and understand. Here's another way, using less Linq.
private List<string> Process(IEnumerable<string> input)
{
List<string> data = new List<string>();
int preExpandCount = 0, offset = 0;
foreach (string inputItem in input)
{
List<string> splitItems = inputItem.Split(',').ToList();
if (data.Count > 0)
preExpandCount = ExpandList(data, splitItems.Count - 1);
offset = 0;
foreach (string splitItem in splitItems)
{
if (preExpandCount == 0)
data.Add(splitItem);
else
{
for (int i = 0; i < preExpandCount; i++)
data[i + offset] = String.Format("{0},{1}", data[i + offset], splitItem);
offset += preExpandCount;
}
}
}
return data.OrderBy(e => e).ToList();
}
private int ExpandList(List<string> existing, int count)
{
int existingCount = existing.Count;
for (int i = 0; i < count; i++)
existing.AddRange(existing.Take(existingCount).ToList());
return existingCount;
}

Split and join multiple logical "branches" of string data

I know there's a couple similarly worded questions on SO about permutation listing, but they don't seem to be quite addressing really what I'm looking for. I know there's a way to do this but I'm drawing a blank. I have a flat file that resembles this format:
Col1|Col2|Col3|Col4|Col5|Col6
a|b,c,d|e|f|g,h|i
. . .
Now here's the trick: I want to create a list of all possible permutations of these rows, where a comma-separated list in the row represents possible values. For example, I should be able to take an IEnumerable<string> representing the above to rows as such:
IEnumerable<string> row = new string[] { "a", "b,c,d", "e", "f", "g,h", "i" };
IEnumerable<string> permutations = GetPermutations(row, delimiter: "/");
This should generate the following collection of string data:
a/b/e/f/g/i
a/b/e/f/h/i
a/c/e/f/g/i
a/c/e/f/h/i
a/d/e/f/g/i
a/d/e/f/h/i
This to me seems like it would elegantly fit into a recursive method, but apparently I have a bad case of the Mondays and I can't quite wrap my brain around how to approach it. Some help would be greatly appreciated. What should GetPermutations(IEnumerable<string>, string) look like?
You had me at "recursive". Here's another suggestion:
private IEnumerable<string> GetPermutations(string[] row, string delimiter,
int colIndex = 0, string[] currentPerm = null)
{
//First-time initialization:
if (currentPerm == null) { currentPerm = new string[row.Length]; }
var values = row[colIndex].Split(',');
foreach (var val in values)
{
//Update the current permutation with this column's next possible value..
currentPerm[colIndex] = val;
//..and find values for the remaining columns..
if (colIndex < (row.Length - 1))
{
foreach (var perm in GetPermutations(row, delimiter, colIndex + 1, currentPerm))
{
yield return perm;
}
}
//..unless we've reached the last column, in which case we create a complete string:
else
{
yield return string.Join(delimiter, currentPerm);
}
}
}
I'm not sure whether this is the most elegant approach, but it might get you started.
private static IEnumerable<string> GetPermutations(IEnumerable<string> row,
string delimiter = "|")
{
var separator = new[] { ',' };
var permutations = new List<string>();
foreach (var cell in row)
{
var parts = cell.Split(separator);
var perms = permutations.ToArray();
permutations.Clear();
foreach (var part in parts)
{
if (perms.Length == 0)
{
permutations.Add(part);
continue;
}
foreach (var perm in perms)
{
permutations.Add(string.Concat(perm, delimiter, part));
}
}
}
return permutations;
}
Of course, if the order of the permutations is important, you can add an .OrderBy() at the end.
Edit: added an alernative
You could also build a list of string arrays, by calculating some numbers before determining the permutations.
private static IEnumerable<string> GetPermutations(IEnumerable<string> row,
string delimiter = "|")
{
var permutationGroups = row.Select(o => o.Split(new[] { ',' })).ToArray();
var numberOfGroups = permutationGroups.Length;
var numberOfPermutations =
permutationGroups.Aggregate(1, (current, pg) => current * pg.Length);
var permutations = new List<string[]>(numberOfPermutations);
for (var n = 0; n < numberOfPermutations; n++)
{
permutations.Add(new string[numberOfGroups]);
}
for (var position = 0; position < numberOfGroups; position++)
{
var permutationGroup = permutationGroups[position];
var numberOfCharacters = permutationGroup.Length;
var numberOfIterations = numberOfPermutations / numberOfCharacters;
for (var c = 0; c < numberOfCharacters; c++)
{
var character = permutationGroup[c];
for (var i = 0; i < numberOfIterations; i++)
{
var index = c + (i * numberOfCharacters);
permutations[index][position] = character;
}
}
}
return permutations.Select(p => string.Join(delimiter, p));
}
One algorithm you can use is basically like counting:
Start with the 0th item in each list (00000)
Increment the last value (00001, 00002 etc.)
When you can't increas one value, reset it and increment the next (00009, 00010, 00011 etc.)
When you can't increase any value, you're done.
Function:
static IEnumerable<string> Permutations(
string input,
char separator1, char separator2,
string delimiter)
{
var enumerators = input.Split(separator1)
.Select(s => s.Split(separator2).GetEnumerator()).ToArray();
if (!enumerators.All(e => e.MoveNext())) yield break;
while (true)
{
yield return String.Join(delimiter, enumerators.Select(e => e.Current));
if (enumerators.Reverse().All(e => {
bool finished = !e.MoveNext();
if (finished)
{
e.Reset();
e.MoveNext();
}
return finished;
}))
yield break;
}
}
Usage:
foreach (var perm in Permutations("a|b,c,d|e|f|g,h|i", '|', ',', "/"))
{
Console.WriteLine(perm);
}
I really thought this would be a great recursive function, but I ended up not writing it that way. Ultimately, this is the code I created:
public IEnumerable<string> GetPermutations(IEnumerable<string> possibleCombos, string delimiter)
{
var permutations = new Dictionary<int, List<string>>();
var comboArray = possibleCombos.ToArray();
var splitCharArr = new char[] { ',' };
permutations[0] = new List<string>();
permutations[0].AddRange(
possibleCombos
.First()
.Split(splitCharArr)
.Where(x => !string.IsNullOrEmpty(x.Trim()))
.Select(x => x.Trim()));
for (int i = 1; i < comboArray.Length; i++)
{
permutations[i] = new List<string>();
foreach (var permutation in permutations[i - 1])
{
permutations[i].AddRange(
comboArray[i].Split(splitCharArr)
.Where(x => !string.IsNullOrEmpty(x.Trim()))
.Select(x => string.Format("{0}{1}{2}", permutation, delimiter, x.Trim()))
);
}
}
return permutations[permutations.Keys.Max()];
}
... my test conditions provided me with exactly the output I expected:
IEnumerable<string> row = new string[] { "a", "b,c,d", "e", "f", "g,h", "i" };
IEnumerable<string> permutations = GetPermutations(row, delimiter: "/");
foreach(var permutation in permutations)
{
Debug.Print(permutation);
}
This produced the following output:
a/b/e/f/g/i
a/b/e/f/h/i
a/c/e/f/g/i
a/c/e/f/h/i
a/d/e/f/g/i
a/d/e/f/h/i
Thanks to everyone's suggestions, they really were helpful in sorting out what needed to be done in my mind. I've upvoted all your answers.

Categories

Resources