返回IQueryable<T>与IEnumerable<T>?有什么区别?
IQueryable<Customer> custs = from c in db.Customers
where c.City == "<City>"
select c;
IEnumerable<Customer> custs = from c in db.Customers
where c.City == "<City>"
select c;
Run Code Online (Sandbox Code Playgroud)
两者都会延迟执行,何时应该优先于另一个?
我知道LINQ to Entities和LINQ to Objects的一些区别,第一个实现IQueryable和第二个实现IEnumerable,我的问题范围在EF 5中.
我的问题是这3种方法的技术差异是什么?我看到,在许多情况下,所有这些都有效.我也看到使用它们的组合.ToList().AsQueryable().
这些方法究竟意味着什么?
是否有任何性能问题或某些因素会导致使用另一个?
例如,为什么会使用?.ToList().AsQueryable()而不是.AsQueryable()?
linq-to-entities entity-framework entity-framework-4 entity-framework-5
通过阅读类似的帖子,我了解到List是一种IEnumerable.但我真的很想知道这两者之间的实际区别是什么.
对于总是使用List并且从未使用IEnumerable的人:
这是一个实际的例子:我们想要存储四个字符串,按字母顺序排序,将它们传递给另一个函数,然后向用户显示结果.我们会用什么?为什么?
希望有人可以为我排序或指出我正确的方向.提前致谢!
我IEnumerable<T>什么时候可以使用...我说List<T>什么?前者优于后者有什么优势?
更新3/31/2017
自从这篇文章以来我已经学到了更多的东西,所以想要ToList从存储库返回时给出一个重要的理由- 调用ToList将(当使用IQueryable时)在数据库上执行已翻译的SQL而不是将记录拉入内存然后过滤.我不相信IEnumerable或IList的隐式转换会这样做.
在MSDN网站上的一些教程之后,我在我的应用程序中使用了通用存储库层.此存储库层由我的服务层调用,而服务层又由控制器调用.
查看通用存储库,获取数据并通过调用返回ToList().但是,方法的返回类型IEnumerable意味着服务层必须接受,IEnumerable并且在返回控制器之前必须再次调用ToList()on IEnumerable.
示例 - 存储库:
public IEnumerable<TEntity> Get(
Expression<Func<TEntity, bool>> filter = null,
Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
string includeProperties = "")
{
IQueryable<TEntity> query = dbSet;
if (filter != null)
{
query = query.Where(filter);
}
foreach (var includeProperty in includeProperties.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
{
query = query.Include(includeProperty);
}
return orderBy != null ? orderBy(query).ToList() : query.ToList();
}
Run Code Online (Sandbox Code Playgroud)
示例 …
我正在做一些关于收益率回归性能的测试,我发现它比正常回报慢.
我测试了值变量(int,double等)和一些引用类型(字符串等)......并且两种情况下的yield return都较慢.为什么要用呢?
看看我的例子:
public class YieldReturnTeste
{
private static IEnumerable<string> YieldReturnTest(int limite)
{
for (int i = 0; i < limite; i++)
{
yield return i.ToString();
}
}
private static IEnumerable<string> NormalReturnTest(int limite)
{
List<string> listaInteiros = new List<string>();
for (int i = 0; i < limite; i++)
{
listaInteiros.Add(i.ToString());
}
return listaInteiros;
}
public static void executaTeste()
{
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
List<string> minhaListaYield = YieldReturnTest(2000000).ToList();
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
ts.Hours, …Run Code Online (Sandbox Code Playgroud) 我遇到了一个逐行读取文件的实现,如下所示:
using (StreamReader reader = File.OpenText(path))
while (!reader.EndOfStream)
{
string line = reader.ReadLine();
}
Run Code Online (Sandbox Code Playgroud)
但就我个人而言,我会这样做:
foreach (string line in File.ReadLines(path))
{
}
Run Code Online (Sandbox Code Playgroud)
有什么理由选择其中之一吗?
最近,我一直在研究一些编写返回集合的函数的约定。我想知道实际上使用a的函数是否List<int>应该返回a List<int>或宁可IList<int>是ICollection<int>or IEnumerable<int>。我创建了一些性能测试,结果令我非常惊讶。
static List<int> list = MakeList();
static IList<int> iList = MakeList();
static ICollection<int> iCollection = MakeList();
static IEnumerable<int> iEnumerable = MakeList();
public static TimeSpan Measure(Action f)
{
var stopWatch = new Stopwatch();
stopWatch.Start();
f();
stopWatch.Stop();
return stopWatch.Elapsed;
}
public static List<int> MakeList()
{
var list = new List<int>();
for (int i = 0; i < 100; ++i)
{
list.Add(i);
}
return list;
}
public static void Main()
{
var time1 …Run Code Online (Sandbox Code Playgroud) 在互联网上搜索C#中的IEnumerable接口是什么?它解决的问题是什么?如果我们不使用它怎么办?但从来没有真正得到太多.很多帖子都解释了如何实现它.
我还发现了以下示例
List<string> List = new List<string>();
List.Add("Sourav");
List.Add("Ram");
List.Add("Sachin");
IEnumerable names = from n in List where (n.StartsWith("S")) select n;
// var names = from n in List where (n.StartsWith("S")) select n;
foreach (string name in names)
{
Console.WriteLine(name);
}
Run Code Online (Sandbox Code Playgroud)
上述输出:
Sourav
萨钦
我想知道,在上面的例子中使用IEnumerable的优势是什么?我可以使用'var'(注释行)来实现相同的功能.
如果你们中的任何人可以帮助我理解这一点并且使用IEnumerable的例子有什么好处,我将不胜感激?如果我们不使用它怎么办?
namespace ConsoleApplication4
{
class T1
{
public int MyProperty { get; set; }
}
class Program
{
static void Main(string[] args)
{
var tmp = (new[] { 1, 3, 4 }).Select(x =>new T1 { MyProperty=x});
foreach (var s in tmp)
{
s.MyProperty = 9;
}
foreach (var s in tmp)
{
Console.WriteLine(s.MyProperty);
}
Console.ReadLine();
}
}
}
Run Code Online (Sandbox Code Playgroud)
我预计屏幕上有三个9,但值仍然相同.
但是,如果我稍微修改代码,则值将成功更改,即:
var tmp = (new[] { 1, 3, 4 }).Select(x =>new T1 { MyProperty=x}).ToList();
Run Code Online (Sandbox Code Playgroud)
我想知道为什么?
问题
当我尝试在async方法中调用我的“ normal”方法时,它将从Debugger 1中被忽略。
这是我的异步方法
internal async static Task<DefinitionsModel> DeserializeAsync(this string path)
{
var model = new DefinitionsModel();
var content = await File.ReadAllTextAsync(path);
model.Pages = content.GetPages();
return model;
}
Run Code Online (Sandbox Code Playgroud)
这是我的“正常”方法
private static IEnumerable<PageModel> GetPages(this string content)
{
var level = 0;
var value = nameof(PageModel.Page).GetDElement<PageModel>();
var start_with_line = $"{level} {value} ";
var end_with_line = string.Concat(Enumerable.Repeat(Environment.NewLine, 2));
var expression = $@"\b{start_with_line}\S * {end_with_line}\b";
var matches = content.GetPagesFromContent(expression);
yield return new PageModel();
}
Run Code Online (Sandbox Code Playgroud)
帮助图片
当我在 Select() 语句的末尾添加 .ToList() 时,它按预期工作。在这种情况下,IEnumerable 和 List 之间有什么区别?
class Foo{
public string Name { get; set; }
public Guid Id { get; set; }
}
class Program
{
static void Main(string[] args)
{
var list = new List<string>(){ "first", "last" };
var bar = list.Select(x => new Foo {
Name = x,
Id = Guid.NewGuid()
}); //.ToList();
Console.WriteLine("bar Count = " + bar.Count());
Console.WriteLine();
for (int i = 0; i < 3; i++) {
Console.WriteLine(bar.First().Name + " " + bar.First().Id); …Run Code Online (Sandbox Code Playgroud) c# ×11
ienumerable ×4
linq ×3
list ×3
.net ×1
.net-core ×1
asp.net-mvc ×1
collections ×1
file-io ×1
foreach ×1
iqueryable ×1
linq-to-sql ×1
performance ×1
readline ×1
select ×1
stream ×1
yield ×1
yield-return ×1