如何从两个List中获取移动组合在 C# 中?
我有两个 List
其中包含
ListOne
A
B
C
ListTwo
A
B
C
D
现在我需要将移动组合获取到列表字符串
因此输出列表将包含
A-B
A-C
A-D
B-C
B-D
C-D
现在我正在使用嵌套 for 循环
为此。? 有没有办法使用LINQ
或LAMBDA EXPRESSION
来做到这一点 请帮助我做到这一点。 预先感谢
示例代码,
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));
但它没有给出正确的输出
It produces like
A-B
A-C
A-D
B-A
B-C
B-D
C-A
C-B
C-D
,但所需的输出就像
A-B
A-C
A-D
B-C
B-D
C-D
使用For循环
的示例代码,
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]);
}
}
它工作正常......但我只需要一个简单的方法(使用LINQ
)
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
)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
进行编辑后,这应该可以解决问题:
保留顺序的第二个版本(ItemFromList1 - ItemFromList2):
Following your edits this should do the trick:
The second version that preserves order (ItemFromList1 - ItemFromList2):
因此,您希望除
,并且没有重复项。
就是这样:
说明要求是战斗的90%。
如果您需要配对中的第一项来自第一个列表,则可以这样做:
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:
列表中添加验证逻辑如何
How about the logic of validating is added to the list
我不认为 LINQ 足够好,我得到了这个,但它不好看:
实际上,当我稍微清理一下嵌套的 foreach 代码时,我比 LINQ 更喜欢它:
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: