0

OK, here is the problem that I am having at the moment: I want to unify same array's elements with each other.

For example: I have an array with these elements "A", "B", "C", "D"

And I want to unify them (possibly then putting them in another List) so it would become:

A,B

A,C

A,D

B,C

B,D

C,D

So far, I have tried a simple for loop but with no success and couldn't think of how to approach this further.

Here is so far what I have tried with no success:

List<string> testList = new List<string>();
List<string> anotherList = new List<string>();

testList.AddRange(richTextBox1.Text.Split(','));
anotherList.ToArray();

for (int i = 0; i < testList.Count; i++) //no idea how to get the right count
{
    var union = testList[i].Union(testList[i+1]);

    foreach (char value in union)
    {
        richTextBox2.Text = value.ToString();
    }
}

Thanks.

Xaruth
  • 4,034
  • 3
  • 19
  • 26
GoldenEyeDog
  • 13
  • 1
  • 4

3 Answers3

3

Perhaps this simple query helps:

var query = from s1 in testList
        from s2 in testList.Skip(1)
        where string.Compare(s1 , s2) < 0
        select string.Format("{0},{1}", s1, s2);
testList = query.ToList();
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
0

this works fine for me to match your desired output

static List<string> list = new List<string> { "A", "B", "C", "D", "E" }; 
static List<string> finished = new List<string>(); 

public static void Main()
{
    for (int i = 0; i < list.Count - 1; i++)
        for (int j = i+1; j < list.Count; j++)
            finished.Add(list[i]+","+list[j]);
}
Jonesopolis
  • 25,034
  • 12
  • 68
  • 112
0

This might be a good start to figure out the "right count"..

http://en.wikipedia.org/wiki/Combination Anyway... You can do something like that (PseudoCode):

List<string> unions = new List<string>();
foreach(string s1 in list1)
{
    foreach(string s2 in list2)
    {
        string union = s1+s2;
        if(!unions.Contains(union))
            unions.Add(union);
    }
}

foreach(string union in unions)
    Console.WriteLine(union);

You could also use some other approach using LINQ's Distinct

LINQ: Distinct values

Community
  • 1
  • 1
Mat
  • 1,960
  • 5
  • 25
  • 38