I'm having two List<String>
which contains
ListOne
A
B
C
ListTwo
A
B
C
D
Now i need to get the moving combinations to a list string
So the output list will contain
A-B
A-C
A-D
B-C
B-D
C-D
Now i'm using Nested for loop
for this.?
Is there any way to do this using LINQ
or LAMBDA EXPRESSION
Please help me to do this.
Thanks in advance
Sample Code
List<String> ListOne = new List<string> { "A","B","C"};
List<String> ListTwo = new List<string> { "A", "B", "C", "D" };
List<String> Result = new List<string>(from X in ListOne
from Y in ListTwo
where X!=Y
select string.Format("{0}-{1}", X, Y));
But its not giving the correct output
It produces like
A-B
A-C
A-D
B-A
B-C
B-D
C-A
C-B
C-D
But the required output is like
A-B
A-C
A-D
B-C
B-D
C-D
Sample Code using For Loop
List<String> ResultTwo = new List<string>();
for (int i = 0; i < ListOne.Count; i++)
{
for (int j = 0; j < ListTwo.Count; j++)
{
if(ListOne[i] != ListTwo[j])
if (ResultTwo.Contains(ListOne[i] + "-" + ListTwo[j]) == false && ResultTwo.Contains(ListTwo[j] + "-" + ListOne[i]) == false)
ResultTwo.Add(ListOne[i] + "-" + ListTwo[j]);
}
}
its working fine.... but i just need a simple way ( Using LINQ
)
Following your edits this should do the trick:
The second version that preserves order (ItemFromList1 - ItemFromList2):
How about the logic of validating is added to the list
I dont think LINQ is good enough for this, I got this, but it is not good looking :
Acualy, when I clean up your nested foreach code a little bit, I like it more than LINQ:
So you want all matches except
and no duplicates.
Here it is:
Stating the requirement is 90% of the battle.
If you NEED the first item in the pairing to come from the first list, this will do it: