LinQ VS普通代码(Sql Data Adapter vs Sql Data Reader) [英] LinQ VS Normal Code (Sql Data Adapter vs Sql Data Reader)

查看:47
本文介绍了LinQ VS普通代码(Sql Data Adapter vs Sql Data Reader)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





在我的代码中实现以下两种方法的最佳方式





Hi,

Which is the best way to implement following two methods in my code


class Sample
{
public string Name {get; set;}
public int ID {get; set;}
}




//Method 1
var list =(from row in ds.Tables[0].AsEnumerable()
                                         select new Sample
                                         {
                                             Name= row.Field<string>("Name"),
                                             ID= row.Field<int>("ID")
                                         }
                                          ).ToList();







//Method 2
List<Sample> sampleList = new List<Sample>(); 
while(sqlDataReader.Read())
{
Sample s1 = new Sample();
s1.Name = (string)sqlDataReader["Name"];
s1.ID = (int)sqlDataReader["ID"];
sampleList.Add(s1);
}





两个代码都可以生成通用列表对象但是,

在第一个方法我正在使用SqlDataAdapter,然后使用LINQ将数据集转换为列表

在第二种方法中,我使用SqlDataReader并将结果转换为列表



我想知道在我的代码中使用这两种技术的正确方法。

我认为方法2是优化的方式......是不是?



问候,

--Sj



both codes can able to generate generic list object but,
in the first method i am using SqlDataAdapter and then convert the dataset to list using LINQ
In the second method, i am using SqlDataReader and convert the result as list

I want to know which the right way of using these two technique in my code.
I thought Method 2 is optimized way... Is it right?

Regards,
--Sj

推荐答案

取决于。



不要结合用于替换彼此的技术。

方法1是LINQ,但它不是LINQ to SQL,因为你使用了几个显式的转换和在数据集对象上 - 实际上这是一种称为 LINQ to DataSet 的现有方法[ ^ ] - 但正如我所见,这只是为了过渡。

我建议您使用 DataSet方法 LINQ to SQL 实体框架

避免在表集合中使用整数索引器。



如果架构简单,并且您不需要双向访问,DataReader可能是一个很好的方法 - 报告就是一个很好的例子。它消耗的资源更少而且速度更快。
It depends.

Don't combine technologies that are meant to replace each-other.
Method 1 is LINQ, but it isn't LINQ to SQL, because you use several explicit casting and that over dataset objects - actually this is an existing approach called LINQ to DataSet[^] - but as I see, this was meant only for transition.
I suggest you use either DataSet approach or LINQ to SQL, or Entity Framework.
Avoid using the integer indexer over the tables collection.

DataReader can be a good approach if the schema is simple, and you don't need bidirectional access - reporting is a good example. It consumes less resources and it is fast.


Method1更快。 Linq具有处理内存的能力。并且易于管理。

如果您想在系统中使用可用内核,则linq是最佳选择。你很容易parallalize。



还有一件重要的事情是你的代码还没有执行,直到你使用变量列表。
Method1 is faster. Linq is having capability of handling memory. And easy to manage.
In case you want to utilize available cores in your system linq is the best option. you can easly parallalize.

And one more important thing is your code is not executed yet, until you consume variable list.


这篇关于LinQ VS普通代码(Sql Data Adapter vs Sql Data Reader)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆