本文介绍了我们可以在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
推荐答案
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);
}
}
这篇关于我们可以在foreach中使用多个对象吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!