c# 读出 list
时间: 2023-11-17 15:07:51 浏览: 42
要读出 C# 中的 List,可以使用 foreach 循环遍历每个元素,或者通过索引访问每个元素。以下是示例代码:
```csharp
List<int> numbers = new List<int> { 1,2, 3, 4, 5 };
// 使用 foreach 循环遍历每个元素
foreach (int number in numbers)
{
Console.WriteLine(number);
}
// 或者使用索引访问每个元素
for (int i = 0; i < numbers.Count; i++)
{
Console.WriteLine(numbers[i]);
}
```
相关问题
C# 泛型 list
可以使用以下代码将C#中的List转换为DataTable:
```csharp
public static DataTable ConvertToDataTable<T>(List<T> list)
{
DataTable table = new DataTable();
PropertyInfo[] properties = typeof(T).GetProperties();
foreach (PropertyInfo property in properties)
{
table.Columns.Add(property.Name, Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType);
}
foreach (T item in list)
{
DataRow row = table.NewRow();
foreach (PropertyInfo property in properties)
{
row[property.Name] = property.GetValue(item) ?? DBNull.Value;
}
table.Rows.Add(row);
}
return table;
}
```
使用方法:
```csharp
List<MyClass> myList = new List<MyClass>();
// 添加数据到 myList
DataTable myTable = ConvertToDataTable(myList);
```
其中,MyClass是自定义的类,需要根据实际情况进行修改。
c# List添加List
在C#中,如果你想要将一个`List`添加到另一个`List`中,可以使用`AddRange`方法。下面是一个例子:
```csharp
List<int> list1 = new List<int>() { 1, 2, 3 };
List<int> list2 = new List<int>() { 4, 5, 6 };
list1.AddRange(list2);
```
在上面的例子中,我们创建了两个整型的`List`对象`list1`和`list2`,并分别添加了一些元素。然后,我们使用`AddRange`方法将`list2`中的所有元素添加到`list1`中。现在,`list1`中的元素为`{ 1, 2, 3, 4, 5, 6 }`。
注意,`AddRange`方法接受一个`IEnumerable`类型的参数,因此可以传递任何实现`IEnumerable`接口的集合类型,不仅仅是`List`类型。