我们可以在foreach中使用多个对象吗? [英] Can we use multiple objects in foreach

查看:106
本文介绍了我们可以在foreach中使用多个对象吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

foreach (object New in data1;object old in data2)
{

}



有可能吗?

我需要从数据库中获取两个对象并将它们都附加到另一个一个


Is it possible?
I need to fetch two objects from a database and append both of them to another one

推荐答案

不是直接但你可以试试LINQ:

Not directly but you can try with LINQ :
foreach( var both in listA.Zip(listB, (a,b)=> new { a, b}))
    {
          both.a.Print();
          both.b.Print();
    }





示例代码:



Sample code:

void Main()
{
	List<A> listA = new List<A>(){ new A("aaa1"), new A("aaa2")};
	List<B> listB = new List<B>(){ new B("bbb1"), new B("bbb3")};
	foreach( var both in listA.Zip(listB, (a,b)=> new { a, b}))
	{
	      both.a.Print();
		  both.b.Print();
	}
}

public class A
{
    public string Val{ get; set;}
     public A( string a)
	{ 
	  Val =a;
	}
    public void Print()
	{
	   Console.WriteLine( "Class A:"+Val);
	}
}

public class B
{
    public string Val{ get; set;}
    public B( string b)
	{ 
	   Val =b;
	}
	public void Print()
	{
	   Console.WriteLine( "Class B:"+Val);
	}
}


没有。但是您可以使用LINQ替代方法,例如JOIN或ZIP方法,它们允许您将两个集合合并为一个。然后,您可以迭代组合集合以获得所需的值。
No. But there are LINQ alternatives which you can use such as JOIN or ZIP method which will allow you to combine two collections into one. Then you can iterate over combined collection to get the desired value.


这篇关于我们可以在foreach中使用多个对象吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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