如何使用泛型列表通用函数接收? [英] how to use generic list Received by generic function ?
问题描述
我有一个有两个属性的类,我用linq查询填写
i have a class with two property and i fill that with linq query
public class a
{
public int ID { set; get; }
public string Name { set; get; }
}
通过
现在我将我的通用列表传递给下面的函数
passed
now i passed my generic list to the below function
List<a> a1 = new List<a>();
a1 = (from p in context.TblTest select new a { ID = p.ID, Name = p.Name }).ToList();
TestFunction(a1);
我的问题是如何在函数中使用数据?
my problem is how to use data in function?
static public void WriteToFile<T>(List<T> YourList)
{
//here
// how to use ?
}
i当我发送List< anyclass>这个函数将函数写入excel文件
像这样
i want when i send List<anyclass> to this function the function writ data to excel file
like this
for (int i = 0; i < YourList.count(); i++) excelWorksheet.Cells[i + 1, "A"] = //here what can i to do ;
推荐答案
你只需阅读泛型;只有一个答案对你没什么帮助: http://msdn.microsoft.com/en-us/ library / 512aeb7t.aspx [ ^ ]。
在你的情况下,看看这个:
You just need to read on generics; just one answer won't help you much: http://msdn.microsoft.com/en-us/library/512aeb7t.aspx[^].
In your case, look at this:
static public void WriteToFile<T>(List<T> yourList)
{
if (yourList == null) return;
if (yourList.Count < 1) return;
T first = yourList[0]; // look here
//...
}
我想你只想迭代基于for循环的列表项索引
I think you just want to iterate through the list items index based in for loop
static public void WriteToFile<T>(List<T> YourList)
{
for (int i = 0; i < YourList.count(); i++)
{
excelWorksheet.Cells[i + 1, "A"] = yourList[i].ID;
excelWorksheet.Cells[i + 1, "B"] = yourList[i].Name;
}
}
或者应该使用foreach语句如
foreach(你的列表中的var项目)
{
//你应该增加我
excelWorksheet.Cells [i + 1,A] = item.ID;
}
希望这有帮助
Or should be using foreach statement like
foreach(var item in yourList)
{
// you should increment i
excelWorksheet.Cells[i + 1, "A"] = item.ID;
}
Hope this helps
这篇关于如何使用泛型列表通用函数接收?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!