Some weird but pretty code trick.
It is c#?
It is c#?
var hash = new Hash{ a => "A value", b => "B value" }; Console.WriteLine(hash["a"]);
Tiny notes from everyday work. Mostly about .NET, C# and some tools I use every day.
var hash = new Hash{ a => "A value", b => "B value" }; Console.WriteLine(hash["a"]);
var stackTrace = new StackTrace(true);
foreach (var r in stackTrace.GetFrames())
{
Console.WriteLine("Filename: {0} Method: {1} Line: {2} Column: {3} ",
r.GetFileName(),r.GetMethod(), r.GetFileLineNumber(),
r.GetFileColumnNumber() );
}
Console.WriteLine(Environment.StackTrace);
void Print(TextWriter writer)
{
// ...
}
using (Stream stream = GetOutputStream()){
var streamWriter = new StreamWriter(stream);
Print(streamWriter);
}
namespace System
{
public static class StringExtensions
{
public static string Fmt(this string format, params object[] args)
{
return string.Format(format, args);
}
}
}
enumerable.Count() > 0
enumerable.Any()
from x in enumerable orderby x.Item1 orderby x.Item2 select x;Your collection will be ordered by x.Item2, not by x.Item1 then by x.Item2. Instead use:
from x in enumerable orderby x.Item1, x.Item2 select x;The same is applicable for extensions methods.
var ordered = enumerable.OrderBy(x=>x.Item1).OrderBy(x=>x.Item2);Correct:
var ordered = enumerable.OrderBy(x=>x.Item1).ThenBy(x=>x.Item2);
foreach (var x in enumerable)
{
var some = enumerable2.Where(y => y == x);
list.Add(some);
}
As far as x is closed, you probably assume that 'some' will depend on each item from 'enumerable'. But actually, 'x' is defined outside of foreach (due to C# implementation), so all 'some's will be calculated using the last value. To prevent this, either fold all enumerables (in general - all lazy calculations) inside blocks, or use locally scoped variables.foreach (var x in enumerable)
{
var local = x;
var some = enumerable2.Where(y => y == local);
list.Add(some);
}
Fortunately, Resharper will not let you forget about this.public IEnumerable CreateList(Type elementType, int capacity)
{
Type listType = typeof(List<>).CreateGenericType(elementType);
return (IEnumerable)Activator.CreateInstance(listType, capacity);
}
var entities = from e in list
where e.Id > 10
select e.Name;
var entities = list.Where(e=>e.Id > 10).Select(e=>e.Name);