将DataReader转换为C#对象

问题描述

我上课

public class Person
{
 public string Name {get; set;}
 public List<string> Friends {get; set;}
}

我有一个数据读取器,该数据读取器从数据库中获取了这些值,我想使用DataReader填充上述类。

通常情况如下所示

Name    Friends
John    Caleb
John    Matthew
John    Simon
Andrew  Bolton
Andrew  Mark

我需要根据名称将其分组,并为每个名称填充“朋友列表”类。

有人可以帮忙吗?我无法获得分组好友列表。什么是实现此逻辑的正确代码。 谢谢

解决方法

我认为您的餐桌像 (姓名,朋友)

您必须在友谊表中阅读

然后您必须将它们分组 喜欢

var groupedTempList = tempList.GroupBy(a=>a.Name)

然后

List<Person> t = new List<Person>();

foreach(var Item in groupedTempList) 
{ 
    Person tP = new Person() {Name = Item.Key};
    foreach(YourTableEquivalentClass subitem in Item)
    {
        tP.Friends.Add(subitem.Friend);
    }
}

这里是dbreader的扩展名:

    public static int? GetNullableInteger(this SqlDataReader dbReader,string name)
    {
        var tVal = dbReader[name];
        if (Convert.IsDBNull(tVal)) return null;
        return new int?(int.Parse(tVal.ToString()));
    }

    public static int GetInteger(this SqlDataReader dbReader,string name)
    {
        int? tVal = dbReader.GetNullableInteger(name);
        if (tVal == null) throw new ArgumentNullException("Der abgerufene int/int ist null/DbNull!");
        return (int)tVal;
    }


    public static string GetString(this SqlDataReader dbReader,string name)
    {
        var tVal = dbReader[name];
        if (Convert.IsDBNull(tVal)) return null;
        return tVal.ToString();
    }

读东西

                List<YourTableEquivalentClass> temp = new List<YourTableEquivalentClass>();
                string sqlComStr =
                      @"SELECT [Name],[Friend]
                          FROM [YourDadabase].[dbo].[YourFriendshipTable]";
                using (SqlConnection con = new SqlConnection(YourConnectionString))
                {
                    con.Open();
                    using (SqlCommand sqlCom = new SqlCommand(sqlComStr,con))
                    {
                        using (SqlDataReader dbReader = sqlCom.ExecuteReader())
                        {
                            if (dbReader.HasRows)
                            {
                                while (dbReader.Read())
                                {
                                    temp.Add(new YourTableEquivalentClass()
                                    {
                                        Name = dbReader.GetString("Name"),Friend = dbReader.GetString("Friend")
                                    });
                                }
                            }
                        }
                    }
                }

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...