如何从两个运动组合列表<串GT;在C#中? [英] How to get moving combination from two List<String> in C#?
本文介绍了如何从两个运动组合列表<串GT;在C#中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个列表<弦乐>
包含
ListOne
A
B
C
ListTwo
A
B
C
D
现在我需要得到移动组合到一个列表字符串
Now i need to get the moving combinations to a list string
因此,输出列表将包含
A-B
A-C
A-D
B-C
B-D
C-D
现在我使用嵌套循环
这个?
有没有办法做到这一点使用 LINQ
或 lambda表达式
请帮我做这个。提前
谢谢
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
示例代码
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
但需要的输出是像
A-B
A-C
A-D
B-C
B-D
C-D
使用的示例代码 For循环
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]);
}
}
其做工精细....但我只需要一个简单的方法(使用 LINQ
)
推荐答案
按照你的编辑这应该这样的伎俩:
Following your edits this should do the trick:
List<string> ListOne = new List<string>(){"A","B","C"};
List<string> ListTwo = new List<string>(){ "A","B","C","D"};
var result = from a in ListOne
from b in ListTwo
let condition = a.CompareTo(b)
where condition != 0
select condition < 0 ? a + "-" + b : b + "-" + a;
foreach (var v in result.Distinct())
{
Console.WriteLine(v);
}
这是保持秩序的第二个版本(ItemFromList1 - ItemFromList2):
The second version that preserves order (ItemFromList1 - ItemFromList2):
var result =
from o in
(
from a in ListOne
from b in ListTwo
let condition = a.CompareTo(b)
where condition != 0
select new { a, b, condition }
)
group o by
o.condition < 0 ? o.a + "-" + o.b : o.b + "-" + o.a into g
select g.Select(n => n.a + "-" + n.b).Take(1).ToArray()[0];
这篇关于如何从两个运动组合列表<串GT;在C#中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文