动态追加的foreach语句C#代码 [英] Dynamically append foreach statements to c# code

查看:373
本文介绍了动态追加的foreach语句C#代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我忙在C#项目中,我有一个List {1,2,3}。我想形成列表对象的元素之间的所有可能的匹配。这将是很容易通过使用3 foreach循环做的。

 的foreach(INT之一名单)
{
的foreach(INT两个列表)
{
的foreach(int类型列表三级)
{
// ...
}}}

但是,如果我不知道的列表对象元素的量:我怎么能使用的foreach做所有比赛循环?因此,如果有列表中的6个元素,那么就应该有6潜在的foreach循环...
(我不希望所看到if语句使用,因为它使用了太多的空间)
如果我用foreach循环,我怎么能动态改变在foreach循环中使用的变量的名称? (你可以说:

 串数字+我=新的String(...); //我在哪里=号(INT)

编辑:



输出应该是:

  1,1,1 
1,2,1
1, 2,2
1,2,3
1,3,1
1,3,2
1,3,3
...


解决方案

从你的定义我想你需要一个发电机组。摘自示例< A HREF =http://rosettacode.org/wiki/Power_set#C.23相对=nofollow>这里

 公共静态的IEnumerable< IEnumerable的< T>> GetPowerSet< T>(列表< T>清单)
{从米Enumerable.Range(0,1<
的回报;< list.Count)
选择$ b $从I b在Enumerable.Range(0,list.Count)
,其中(M&安培;(1<< I))!= 0
选择名单由[i];
}

私人无效button1_Click_2(对象发件人,EventArgs五)
{
名单,LT; INT>临时=新的List< INT>(){1,2,3};

名单,LT; IEnumerable的< INT>> AB = GetPowerSet(临时).ToList();
Console.Write(的string.join(Environment.NewLine,
ab.Select(子集= GT;
的string.join(,,subset.Select(CLR = GT; CLR。的ToString())ToArray的()))ToArray的()))。。
}



OUTPUT:

  1 
2
1,2
3
1,3
2,3
1,2, 3


I'm busy on a c# project where I have a List{1,2,3}. I want to form all possible matches between the elements of the List object. That would be easy to do by using 3 foreach loops.

foreach(int one in list)
{
     foreach(int two in list)
     {
           foreach(int three in list)
           {
                  // ...
            }}}

But if I don't know the amount of elements in the list object : how can I do all matches by using foreach loops?So if there are 6 elements in the list, then there should be 6 underlying foreach loops... (I don't want to use if statements as seen as it uses too much space) And if I use foreach loops, how can I dynamically change the name of the variable used in the foreach loop? (Can you say :

     String "number"+i = new String("..."); //where i = number (int)

EDIT :

The output should be :

 1,1,1
 1,2,1
 1,2,2
 1,2,3
 1,3,1
 1,3,2
 1,3,3
 ...

解决方案

From your definition i guess you need a power set. Example taken from here

public static IEnumerable<IEnumerable<T>> GetPowerSet<T>(List<T> list)
{
        return from m in Enumerable.Range(0, 1 << list.Count)
               select
                   from i in Enumerable.Range(0, list.Count)
                   where (m & (1 << i)) != 0
                   select list[i];
}

private void button1_Click_2(object sender, EventArgs e)
{
        List<int> temp = new List<int>() { 1,2,3};

        List<IEnumerable<int>> ab = GetPowerSet(temp).ToList();
        Console.Write(string.Join(Environment.NewLine,
                                 ab.Select(subset =>
                                 string.Join(",", subset.Select(clr => clr.ToString()).ToArray())).ToArray()));
}

OUTPUT:

1
2
1,2
3
1,3
2,3
1,2,3

这篇关于动态追加的foreach语句C#代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆