将数据集转换为列表

本文关键字:列表 转换 数据集 | 更新日期: 2023-09-27 17:52:48

我使用SqlHelper在DB中执行存储过程。

在一个名为constants的命名空间中,我定义了如下内容

public class ShowInstitutes
{
   public string InstituteName { get; set; }
   public string InstituteCity { get; set; }
   public int InstituteId { get; set; }
}

在DAL层中,我试图执行存储过程并获得IList格式的结果

public IList<ShowInstitutes> ShowInstitutes(int instituteId)
{
   return SqlHelper.ExecuteDataset(dBConnection, "usp_SPName");
}

我得到以下错误:

不能隐式转换类型"System.Data"。DataSet' to 'System.Collections.Generic.IList<>

将数据集转换为列表

您可以像这样将您的Dataset结果转换为IList。

public IList<ShowInstitutes> ShowInstitutes(int instituteId)
{
    var dataTable = SqlHelper.ExecuteDataset(dBConnection, "usp_SPName");
    var SourceLists = new List<ShowInstitutes>();
    for (var index = 0; index < dataTable.Rows.Count; index++)
    {
        SourceLists.Add(new ShowInstitutes
        {
            InstituteName = Convert.ToString(dataTable.Rows[index]["Columnname"], CultureInfo.InvariantCulture),
            InstituteCity = Convert.ToString(dataTable.Rows[index]["Columnname"], CultureInfo.InvariantCulture),
            InstituteId = Convert.ToInt32(dataTable.Rows[index]["Columnname"], CultureInfo.InvariantCulture)
        });
    }
    return SourceLists;
}
public IList<ShowInstitutes> ShowInstitutes(int instituteId)
{
   var d = SqlHelper.ExecuteDataset(dBConnection, "usp_SPName");
   var myData = d.Tables[0].AsEnumerable().Select(data => new ShowInstitutes{
       InstituteName = data.Field<string>("InstituteName "),
       InstituteCity = data.Field<string >("InstituteCity "),
       InstituteId = data.Field<int>("InstituteId ")
   });
   var list = myData.ToList();
   return list;
}
public class info
{
    public string counter
    {
        get; set;
    }
    public string age
    {
        get;
        set;
    }
    public string id
    {
        get;
        set;
    }
    public string marks
    {
        get;
        set;
    }
    public string name
    {
        get;
        set;
    }
    public List<info> getdata()
    {
        string c = "Data Source=bla ;bla ;bla";
        SqlConnection con = new SqlConnection(c);
        DataSet ds = SqlHelper.ExecuteDataset(con, CommandType.Text, "SELECT * from table1");
        var list = (ds.Tables[0].AsEnumerable().Select(
            df =>
            new info
            {
                age = df[0].ToString(),
                counter = df[1].ToString(),
                id = df[3].ToString(),
                name = df[4].ToString(),
                marks = df[2].ToString()
            })).ToList();
        return list;
    }
}
class Program
{
    static void Main(string[] args)
    {
        info a =new info();
        List<info> list1= a.getdata();
        foreach (var info in list1)
        {
            Console.WriteLine(info.name+" "+info.age+" "+info.marks);
        }
        Console.Read();
    }
}