- 1
- 2
- 3
- 4
public List<Market> GetMarkets(List<Sport> sports)
{
return (from sport in sports from region in sport.Regions from league in region.Leagues from game in league.Games from market in game.Markets select market).ToList();
}
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
−2
public List<Market> GetMarkets(List<Sport> sports)
{
return (from sport in sports from region in sport.Regions from league in region.Leagues from game in league.Games from market in game.Markets select market).ToList();
}
вонючий код от решарпера
+1
var vals =
tagsTypes.Zip(times,
(tagType, time) =>
{
if (error != null)
return new { time = time, val = (object)ServiceValue.DataSourceNotAvailable };
if (!timedVals.ContainsKey(tagType.tag))
return new { time = time, val = (object)ServiceValue.NoValue };
if (timedVals[tagType.tag].Count == 0)
return new { time = time, val = (object)ServiceValue.NoValue };
var value = timedVals[tagType.tag].Find(x => x.TimestampUTC == time.ToUniversalTime() && x.Value!=null);
if (value != null && value.IsGood())
{
if (value.Value == null)
return new { time = time, val = (object)ServiceValue.Error };
else
{
if (!string.IsNullOrEmpty(value.DigitalSetValue))
return new { time = time, val = (object)value.DigitalSetValue };
return new { time = time, val = value.Value };
}
}
else
{
var val = _connection.GetTagByName(tagType.tag).Data.ArcValue(time, RetrievalTypeConstants.rtAuto);
if (!string.IsNullOrEmpty(val.DigitalSetValue))
return new { time = time, val = (object)val.DigitalSetValue };
return new { time = time, val = val.Value };
}
return new { time = time, val = (object)ServiceValue.Error };
}).ToArray();
давайте ка рассортируем значения по аттрибутам
0
public static int index(string word, char comp)
{
int k = -1;
for (int i = 0; i < word.Length; i++)
if (word[i] == comp)
{
k = i;
break;
}
return k;
}
public static char[] strtocharr(string str)
{
char[] tmp = new char[str.Length];
for (int i = 0; i < tmp.Length; i++)
tmp[i] = str[i];
return tmp;
}
public static string charrtostr(char[] charr)
{
string tmp = null;
for (int i = 0; i < charr.Length; i++)
tmp = String.Format("{0}{1}", tmp, charr[i]);
return tmp;
}
public static char maskfromword(string word)
{
return word[word.Length - 1];
}
public static string maskfromword(string word, int n)
{
string mask = null;
for (int i = 0; i < n; i++)
mask = String.Format("{0}{1}", mask, word[word.Length - 1]);
return mask;
}
public static char Counter(char crnt, string word)
{
if (crnt != maskfromword(word))
crnt = word[index(word, crnt) + 1];
else
crnt = word[0];
return crnt;
}
public static string Counter(string prev, string word, int k)
{
char[] tmp = strtocharr(prev);
if (k >= prev.Length - 1)
k = prev.Length - 1;
else
for (int i = k + 1; i < prev.Length; i++)
tmp[i] = word[0];
if (tmp[k] == maskfromword(word))
return MultiCounter(prev, word, k - 1);
else
tmp[k] = Counter(tmp[k], word);
return charrtostr(tmp);
}
Список методов, позволяющие сделать счетчик по словарю (полезно для генераторов словарей) на любое количество символов.
+3
public bool Success { get; set; }
public bool Failure { get { return !Success; } set { Success = !value; } }
И не поспоришь!
−2
labelViewData.CreateTextPainterAccordingAllowedBoundsForLabels
По Макконнеллу. Название метода должно отражать всю его суть и даже немножко деталей реализации. Ну как немножко, почти все.
0
internal static object CreateDefaultEqualityComparer(Type type)
{
Debug.Assert(type != null && type is RuntimeType);
object result = null;
var runtimeType = (RuntimeType)type;
// Specialize for byte so Array.IndexOf is faster.
if (type == typeof(byte))
{
result = new ByteEqualityComparer();
}
// If T implements IEquatable<T> return a GenericEqualityComparer<T>
else if (typeof(IEquatable<>).MakeGenericType(type).IsAssignableFrom(type))
{
result = CreateInstanceForAnotherGenericParameter((RuntimeType)typeof(GenericEqualityComparer<int>), runtimeType);
}
// Nullable does not implement IEquatable<T?> directly because that would add an extra interface call per comparison.
// Instead, it relies on EqualityComparer<T?>.Default to specialize for nullables and do the lifted comparisons if T implements IEquatable.
else if (type.IsGenericType)
{
if (type.GetGenericTypeDefinition() == typeof(Nullable<>))
{
result = TryCreateNullableEqualityComparer(runtimeType);
}
}
// The equality comparer for enums is specialized to avoid boxing.
else if (type.IsEnum)
{
result = TryCreateEnumEqualityComparer(runtimeType);
}
return result ?? CreateInstanceForAnotherGenericParameter((RuntimeType)typeof(ObjectEqualityComparer<object>), runtimeType);
}
Код взят из CoreCLR mscorlib сырцов.
Внимание вопрос. Нахерна было писать эту обосгость когда данный метод легко делается генериком без какого либо вызова "невидимого" кода?
вот пример как все должно было быть
```
internal static object CreateDefaultEqualityComparer<T>()
{
// Specialize for byte so Array.IndexOf is faster.
if (typeof(T) == typeof(byte))
{
result = new ByteEqualityComparer();
}
// If T implements IEquatable<T> return a GenericEqualityComparer<T>
else if (typeof(IEquatable<T>).IsAssignableFrom( typeof(T)))
{
result new GenericEqualityComparer<T>();
}
// Nullable does not implement IEquatable<T?> directly because that would add an extra interface call per comparison.
// Instead, it relies on EqualityComparer<T?>.Default to specialize for nullables and do the lifted comparisons if T implements IEquatable.
else if (typeof(T).IsGenericType)
{
if (typeof(T).GetGenericTypeDefinition() == typeof(Nullable<>))
{
result = new NullableEqualityComparer<T>();
}
}
// The equality comparer for enums is specialized to avoid boxing.
else if (typeof(T).IsEnum)
{
result = TryCreateEnumEqualityComparer<T>();
}
return result ?? new ObjectEqualityComparer<T>();
}
```
−1
internal static object CopyImmutableSortedDictionary<K, V>(object original, ICopyContext context)
{
return original;
}
Microsoft Orleans https://github.com/dotnet/orleans
Копирование объекта в 2к17
0
public void GetMapping(DbObject obj, IEnumerable<DbObject> map = null, params string[] additional)
{
Mapper m = Mapper.Get(obj.DialectType);
switch (m.MapperType)
{
case MapperType.SST:
m.Initialize(null, additional);
break;
case MapperType.SSM:
m.Initialize(null, additional);
break;
default:
throw new ArgumentException();
}
// применение: этот метод возвращает List<Tupple<DbObject, DbObject>>
m.GetMappingByDialect(obj, map);
}
public enum MapperType
{
SST,
SSM,
}
Во-вторник - этот код, выбил меня из рабочего процесса на весь день ...
0
private void button1_Click(object sender, EventArgs e)
{
short number = 34;
folderBrowserDialog1.ShowDialog();
//fileListBox1.FileName = folderBrowserDialog1.SelectedPath;
DirectoryInfo myFolder = new DirectoryInfo(folderBrowserDialog1.SelectedPath);
foreach (FileInfo T in myFolder.GetFiles())
{
number++;
string filename = T.Name;
File.Move(folderBrowserDialog1.SelectedPath + "" + filename, folderBrowserDialog1.SelectedPath + "" + number.ToString());
}
}
}
}
Решил я тут старые проекты копнуть...
0
public bool CheckBool(string value)
{
value = value.ToLower();
return !string.IsNullOrEmpty(value) && (value == "on" || value == "yes" || value == "1") ? true : false;
}
another variant ;D