使用集合我有两种获取对象计数的方法; Count(属性)和Count()方法.谁知道关键的区别是什么?我可能错了,但我总是在任何条件语句中使用Count属性,因为我假设Count()方法对集合执行某种查询,其中Count必须在我获得之前已经分配.但这是一个猜测 - 如果我错了,我不知道性能是否会受到影响.
编辑:出于好奇,那么,如果集合为空,Count()会抛出异常吗?因为我很确定Count属性只返回0.
我一直在寻找之间的性能基准测试Contains
,Exists
以及Any
方法可用List<T>
.我只想出于好奇而发现这一点,因为我总是在这些中感到困惑.关于SO的许多问题描述了这些方法的定义,例如:
所以我决定自己做.我将其添加为答案.对结果有任何更多见解是最受欢迎的.我还对数组进行了基准测试以查看结果
我有ReSharper 4.5并且到目前为止发现它非常宝贵,但我有一个顾虑;
它似乎想要隐含每个变量声明(var).
作为一个相对较新的开发人员,在这方面我应该相信ReSharper多少钱?
从Paints Tab Headers的方法中获取以下代码片段.
TabPage currentTab = tabCaseNotes.TabPages[e.Index];
Rectangle itemRect = tabCaseNotes.GetTabRect(e.Index);
SolidBrush fillBrush = new SolidBrush(Color.Linen);
SolidBrush textBrush = new SolidBrush(Color.Black);
StringFormat sf = new StringFormat
{
Alignment = StringAlignment.Center,
LineAlignment = StringAlignment.Center
};
Run Code Online (Sandbox Code Playgroud)
Resharper希望我将所有5个改为var.我已经阅读了以下类似帖子,在C#中使用var关键字,但我想从ReSharper的角度来看.
当我在寻找Count 和 Count() 之间的区别时,我想看一眼Count()
. 我看到以下代码片段,我想知道为什么checked
需要/需要关键字:
int num = 0;
using (IEnumerator<TSource> enumerator = source.GetEnumerator())
{
while (enumerator.MoveNext())
{
num = checked(num + 1);
}
return num;
}
Run Code Online (Sandbox Code Playgroud)
源代码:
// System.Linq.Enumerable
using System.Collections;
using System.Collections.Generic;
public static int Count<TSource>(this IEnumerable<TSource> source)
{
if (source == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.source);
}
ICollection<TSource> collection = source as ICollection<TSource>;
if (collection != null)
{
return collection.Count;
}
IIListProvider<TSource> iIListProvider = source as IIListProvider<TSource>;
if (iIListProvider != null)
{
return …
Run Code Online (Sandbox Code Playgroud) 有没有办法使用一个循环,它取一个大列表中的前100项,与它们做一些事情,然后下一个100等,但当它接近结束时,它会自动缩短"100"步骤到剩余的项目.
目前我必须使用两个if循环:
for (int i = 0; i < listLength; i = i + 100)
{
if (i + 100 < listLength)
{
//Does its thing with a bigList.GetRange(i, 100)
}
else
{
//Does the same thing with bigList.GetRange(i, listLength - i)
}
}
Run Code Online (Sandbox Code Playgroud)
有没有更好的方法呢?如果不是,我将至少使"事物"成为一个函数,因此代码不必被复制两次.
任何人都可以解释这行代码吗?
bool status = datacontext.tblTransactionDetails.Where(x => x.AdvertID == app.AdvertID && x.IsActive == true).FirstOrDefault() == null ? false : true;
Run Code Online (Sandbox Code Playgroud) 在这种情况下,我有两个不同的LINQ表达式来从两个不同条件的产品计数.我只是好奇是否可以从一个LINQ表达式中检索这两个计数?
class Program
{
static void Main(string[] args)
{
List<Product> Products = new List<Product>()
{
new Product() { ID = 1 },
new Product() { ID = 2 },
new Product() { ID = 3 },
new Product() { ID = 4 },
new Product() { ID = 5 },
new Product() { ID = 6 }
};
int all = Products.Count();
int some = Products.Where(x => x.ID < 2).Count();
}
}
public class Product
{
public int ID { …
Run Code Online (Sandbox Code Playgroud) c# ×6
linq ×3
list ×2
.net ×1
benchmarking ×1
checked ×1
collections ×1
count ×1
implicit ×1
loops ×1
performance ×1
range ×1
resharper ×1