如何从两个List中获取移动组合在 C# 中?

发布于 2024-10-08 10:42:09 字数 1843 浏览 2 评论 0原文

我有两个 List 其中包含

ListOne
          A
          B
          C
ListTwo
          A
          B
          C
          D

现在我需要将移动组合获取到列表字符串

因此输出列表将包含

         A-B
         A-C
         A-D
         B-C
         B-D
         C-D

现在我正在使用嵌套 for 循环 为此。? 有没有办法使用LINQLAMBDA 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

好多鱼好多余 2024-10-15 10:42:09

进行编辑后,这应该可以解决问题:

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):

        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];

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);
}

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];
丑丑阿 2024-10-15 10:42:09

因此,您希望除

  • 与自身匹配的项目
  • 之外的所有匹配项与较小的项目匹配

,并且没有重复项。

就是这样:

IEnumerable<string> result = 
  (
    from a in ListOne
    from b in ListTwo
    where a != b
    select a.CompareTo(b) < 0 ? a + "-" + b : b + "-" + a
  ).Distinct();

说明要求是战斗的90%。


如果您需要配对中的第一项来自第一个列表,则可以这样做:

IEnumerable<string> result = 
  (
    from a in ListOne
    from b in ListTwo
    select new
    {
      A = a,
      B = b,
      Combo = a.CompareTo(b) < 0 ? a + "-" + b : b + "-" + a
    } into x
    group x by x.Combo into g
    select g.Select(x2 => x2.A + "-" + x2.B).First()
  )

So you want all matches except

  • item matched to itself
  • item matched to smaller item

and no duplicates.

Here it is:

IEnumerable<string> result = 
  (
    from a in ListOne
    from b in ListTwo
    where a != b
    select a.CompareTo(b) < 0 ? a + "-" + b : b + "-" + a
  ).Distinct();

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:

IEnumerable<string> result = 
  (
    from a in ListOne
    from b in ListTwo
    select new
    {
      A = a,
      B = b,
      Combo = a.CompareTo(b) < 0 ? a + "-" + b : b + "-" + a
    } into x
    group x by x.Combo into g
    select g.Select(x2 => x2.A + "-" + x2.B).First()
  )
水中月 2024-10-15 10:42:09
var listA = new List<string> { "A", "B", "C" };
var listB = new List<string> { "A", "B" };
var result = listA.SelectMany((a, indexA) =>
                     listB.Where((b, indexB) => 
                            listB.Contains(a) ? !b.Equals(a)&&indexB > indexA 
                                              : !b.Equals(a))
                          .Select(b => string.Format("{0}-{1}", a, b)));
var listA = new List<string> { "A", "B", "C" };
var listB = new List<string> { "A", "B" };
var result = listA.SelectMany((a, indexA) =>
                     listB.Where((b, indexB) => 
                            listB.Contains(a) ? !b.Equals(a)&&indexB > indexA 
                                              : !b.Equals(a))
                          .Select(b => string.Format("{0}-{1}", a, b)));
蓝礼 2024-10-15 10:42:09

列表中添加验证逻辑如何

class Program
{
    static void Main(string[] args)
    {
        List<string> a = new List<string>() { "C", "D", "L" };
        List<string> b = new List<string>() { "C", "L", "C", "D" };

        var pairValuesNotEqual = from vara in a
                from varb in b
                where vara != varb
                select new Pair(vara, varb);


        Set sets = new Set();
        sets.AddRange(pairValuesNotEqual);

        foreach (var item in sets)
        {
            Console.WriteLine(item.First + " - " + item.Second);
        }

        Console.ReadLine();
    }
}

public class Set : List<Pair>
{
    public new void AddRange(IEnumerable<Pair> pairs)
    {
        foreach (var item in pairs)
        {
            this.Add(item);
        }
    }

    public new void Add(Pair item)
    {
        if (!IsExists(item))
            base.Add(item);
    }

    private bool IsExists(Pair item)
    {
        foreach (Pair i in this)
        {
            if (i.First == item.Second && i.Second == item.First)
                return true;
        }

        return false;
    }
}

How about the logic of validating is added to the list

class Program
{
    static void Main(string[] args)
    {
        List<string> a = new List<string>() { "C", "D", "L" };
        List<string> b = new List<string>() { "C", "L", "C", "D" };

        var pairValuesNotEqual = from vara in a
                from varb in b
                where vara != varb
                select new Pair(vara, varb);


        Set sets = new Set();
        sets.AddRange(pairValuesNotEqual);

        foreach (var item in sets)
        {
            Console.WriteLine(item.First + " - " + item.Second);
        }

        Console.ReadLine();
    }
}

public class Set : List<Pair>
{
    public new void AddRange(IEnumerable<Pair> pairs)
    {
        foreach (var item in pairs)
        {
            this.Add(item);
        }
    }

    public new void Add(Pair item)
    {
        if (!IsExists(item))
            base.Add(item);
    }

    private bool IsExists(Pair item)
    {
        foreach (Pair i in this)
        {
            if (i.First == item.Second && i.Second == item.First)
                return true;
        }

        return false;
    }
}
_失温 2024-10-15 10:42:09

我不认为 LINQ 足够好,我得到了这个,但它不好看:

        var A = from one in ListOne
                from two in ListTwo
                where one != two
                let x = one.CompareTo(two) < 0 ? one : two
                let y = one.CompareTo(two) < 0 ? two : one
                select new { X = x, Y = y};

        var B = A.Distinct().Select(a => a.X + "-" + a.Y);

实际上,当我稍微清理一下嵌套的 foreach 代码时,我比 LINQ 更喜欢它:

        List<string> outList = new List<string>();
        foreach (string s1 in ListOne)
        {
            foreach (string s2 in ListTwo)
            {
                if (s1 != s2 &&
                    !outList.Contains(s1 + "-" + s2) &&
                    !outList.Contains(s2 + "-" + s1))
                {
                    outList.Add(s1 + "-" + s2);
                }
            }
        }

I dont think LINQ is good enough for this, I got this, but it is not good looking :

        var A = from one in ListOne
                from two in ListTwo
                where one != two
                let x = one.CompareTo(two) < 0 ? one : two
                let y = one.CompareTo(two) < 0 ? two : one
                select new { X = x, Y = y};

        var B = A.Distinct().Select(a => a.X + "-" + a.Y);

Acualy, when I clean up your nested foreach code a little bit, I like it more than LINQ:

        List<string> outList = new List<string>();
        foreach (string s1 in ListOne)
        {
            foreach (string s2 in ListTwo)
            {
                if (s1 != s2 &&
                    !outList.Contains(s1 + "-" + s2) &&
                    !outList.Contains(s2 + "-" + s1))
                {
                    outList.Add(s1 + "-" + s2);
                }
            }
        }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文