在日常的C#/.NET开发中,我们可能会遇到这样的需求,即本文标题所述:将泛型对象集合(List
///
/// 分类目录实体--测试类
///
public class Category
{
///
/// ID
///
public int Id { get; set; }
///
/// 语言名称
///
public string Language { get; set; }
///
/// 别名
///
public string Alias { get; set; }
}
并有一个相关的泛型集合:
_categories = new List
{
new Category{Id=1,Language="C#",Alias="csharp"},
new Category{Id=2,Language="C",Alias="c"},
new Category{Id=3,Language="C++",Alias="cpp"},
new Category{Id=4,Language="Javascript",Alias="javascript"}
};
如果要基于这个泛型集合,转换成属性对应的二维数组(如下所示),你的实现思路是如何呢?
[[1,"C#"],[2,"C"],[3,"C++"],[4,"Javascript"]]
本文分享一个C#/.NET中泛型对象集合(List
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
namespace ConsoleApp2
{
public class Program
{
private static List _categories;
static void Main(string[] args)
{
BuildData();
DoTest();
Console.ReadKey();
}
///
/// 测试的方法
///
static void DoTest()
{
//只读取ID属性
var array = _categories.To2DArray(x => x.Id);
//注意:为便于显示转换结果,本示例使用了第三方的组件--Newtonsoft.Json
Console.WriteLine(JsonConvert.SerializeObject(array));
/*
* 输出结果:
* [[1],[2],[3],[4]]
*/
//读取ID,Language属性
array = _categories.To2DArray(x => x.Id, x => x.Language);
Console.WriteLine(JsonConvert.SerializeObject(array));
/*
* 输出结果:
* [[1,"C#"],[2,"C"],[3,"C++"],[4,"Javascript"]]
*/
//读取ID,Language,Alias属性
array = _categories.To2DArray(x => x.Id, x => x.Language, x => x.Alias);
Console.WriteLine(JsonConvert.SerializeObject(array));
/*
* 输出结果:
* [[1,"C#","csharp"],[2,"C","c"],[3,"C++","cpp"],[4,"Javascript","javascript"]]
*/
}
///
/// 模拟测试数据
///
static void BuildData()
{
_categories = new List
{
new Category{Id=1,Language="C#",Alias="csharp"},
new Category{Id=2,Language="C",Alias="c"},
new Category{Id=3,Language="C++",Alias="cpp"},
new Category{Id=4,Language="Javascript",Alias="javascript"}
};
}
}
///
/// 分类目录实体--测试类
///
public class Category
{
///
/// ID
///
public int Id { get; set; }
///
/// 语言名称
///
public string Language { get; set; }
///
/// 别名
///
public string Alias { get; set; }
}
///
/// 实现泛型集合到数组对象转换的静态扩展类
///
public static class ConverterExtension
{
///
/// 实现泛型集合到数组对象转换的静态扩展方法
///
/// 泛型对象
/// 泛型集合
/// 需要转换的泛型对象属性
/// 数据对象
public static object[,] To2DArray(this List lines, params Func[] lambdas)
{
var array = new object[lines.Count(), lambdas.Count()];
var lineCounter = 0;
lines.ForEach(line =>
{
for (var i = 0; i < lambdas.Length; i++)
{
array[lineCounter, i] = lambdas[i](line);
}
lineCounter++;
});
return array;
}
}
}
测试运行结果为:
本文同步发表至 码友网 : C#/.NET中泛型对象集合(List