Here are the examples of the csharp api System.Linq.IOrderedEnumerable.ThenBy(System.Func) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
542 Examples
19
Source : TagModule.cs
with MIT License
from discord-csharp
with MIT License
from discord-csharp
private Embed BuildEmbed(IReadOnlyCollection<TagSummary> tags, IUser ownerUser = null, IGuild ownerGuild = null, IRole ownerRole = null)
{
var orderedTags = tags
.OrderByDescending(x => x.Uses)
.ThenBy(x => x.Name);
var ownerName = ownerUser?.Username
?? ownerGuild?.Name
?? ownerRole?.Name;
var ownerImage = ownerUser?.GetDefiniteAvatarUrl()
?? ownerGuild?.IconUrl;
var builder = new EmbedBuilder();
builder
.WithAuthor(ownerName, ownerImage)
.WithColor(Color.DarkPurple)
.WithDescription(tags.Count > 0 ? null : "No tags.")
.WithFooter(EmbedFooterText)
.Withreplacedle("Tags");
const int tagsToDisplay = 6;
foreach (var tag in orderedTags.Take(tagsToDisplay))
{
builder.AddField(tag.Name, $"{tag.Uses} uses", true);
}
if (tags.Count > tagsToDisplay)
{
var fieldName = $"and {tags.Count - tagsToDisplay} more";
// https://modix.gg/tags
var url = new UriBuilder(Config.WebsiteBaseUrl)
{
Path = "/tags"
}.RemoveDefaultPort().ToString();
builder.AddField(x => x.WithName(fieldName)
.WithValue($"View at {url}"));
}
return builder.Build();
}
19
Source : MoneyColumnMetadataModel.cs
with GNU General Public License v3.0
from DiverOfDark
with GNU General Public License v3.0
from DiverOfDark
public static IEnumerable<MoneyColumnMetadataModel> SortColumns(this IEnumerable<MoneyColumnMetadataModel> self)
{
return self.OrderByDescending(v => v.IsComputed).ThenBy(v => v.Provider).ThenBy(v => v.Order)
.ThenBy(v => v.AccountName);
}
19
Source : Claims.cs
with MIT License
from dolittle
with MIT License
from dolittle
public bool Equals(Claims other)
{
if (other == null || other.Count() != this.Count())
return false;
var thisClaims = _claims.OrderBy(_ => _.Name).ThenBy(_ => _.ValueType).ThenBy(_ => _.Value).ToArray();
var otherClaims = other.OrderBy(_ => _.Name).ThenBy(_ => _.ValueType).ThenBy(_ => _.Value).ToArray();
for (var i = 0; i < thisClaims.Length; i++)
{
if (!object.Equals(thisClaims[i], otherClaims[i]))
{
return false;
}
}
return true;
}
19
Source : Claims.cs
with MIT License
from dolittle
with MIT License
from dolittle
public override int GetHashCode()
{
var array = _claims.OrderBy(_ => _.Name).ThenBy(_ => _.ValueType).ThenBy(_ => _.Value).ToArray();
return HashCodeHelper.GetHashCode(array);
}
19
Source : GetBetrayalCheatsheetHandler.cs
with MIT License
from domialex
with MIT License
from domialex
public Task<BetrayalLeague> Handle(GetBetrayalCheatsheetQuery request, CancellationToken cancellationToken)
{
var agents = new List<BetrayalAgent>();
agents.Add(new BetrayalAgent(resources.AislingName, "Aisling.png", RewardValue.Low)
{
Transportation = new BetrayalReward(resources.AislingTransportation, RewardValue.NoValue),
Fortification = new BetrayalReward(resources.AislingFortification, RewardValue.NoValue),
Research = new BetrayalReward(resources.AislingResearch, RewardValue.Medium, resources.AislingResearchTooltip),
Intervention = new BetrayalReward(resources.AislingIntervention, RewardValue.Low)
});
agents.Add(new BetrayalAgent(resources.CameriaName, "Cameria.png", RewardValue.High)
{
Transportation = new BetrayalReward(resources.CameriaTransportation, RewardValue.Medium, resources.CameriaTransportationTooltip),
Fortification = new BetrayalReward(resources.CameriaFortification, RewardValue.Medium),
Research = new BetrayalReward(resources.CameriaResearch, RewardValue.Medium),
Intervention = new BetrayalReward(resources.CameriaIntervention, RewardValue.High)
});
agents.Add(new BetrayalAgent(resources.ElreonName, "Elreon.png", RewardValue.NoValue)
{
Transportation = new BetrayalReward(resources.ElreonTransportation, RewardValue.Low),
Fortification = new BetrayalReward(resources.ElreonFortification, RewardValue.Low),
Research = new BetrayalReward(resources.ElreonResearch, RewardValue.Low),
Intervention = new BetrayalReward(resources.ElreonIntervention, RewardValue.Low)
});
agents.Add(new BetrayalAgent(resources.GraviciusName, "Gravicius.png", RewardValue.High)
{
Transportation = new BetrayalReward(resources.GraviciusTransportation, RewardValue.Medium),
Fortification = new BetrayalReward(resources.GraviciusFortification, RewardValue.Low),
Research = new BetrayalReward(resources.GraviciusResearch, RewardValue.NoValue),
Intervention = new BetrayalReward(resources.GraviciusIntervention, RewardValue.High)
});
agents.Add(new BetrayalAgent(resources.GuffName, "Guff.png", RewardValue.Medium)
{
Transportation = new BetrayalReward(resources.GuffTransportation, RewardValue.Medium, resources.GuffTransportationTooltip),
Fortification = new BetrayalReward(resources.GuffFortification, RewardValue.Low, resources.GuffFortificationTooltip),
Research = new BetrayalReward(resources.GuffResearch, RewardValue.Low),
Intervention = new BetrayalReward(resources.GuffIntervention, RewardValue.Low, resources.GuffInterventionTooltip)
});
agents.Add(new BetrayalAgent(resources.HakuName, "Haku.png", RewardValue.Medium)
{
Transportation = new BetrayalReward(resources.HakuTransportation, RewardValue.NoValue),
Fortification = new BetrayalReward(resources.HakuFortification, RewardValue.NoValue),
Research = new BetrayalReward(resources.HakuResearch, RewardValue.NoValue),
Intervention = new BetrayalReward(resources.HakuIntervention, RewardValue.Medium)
});
agents.Add(new BetrayalAgent(resources.HillockName, "Hillock.png", RewardValue.Low)
{
Transportation = new BetrayalReward(resources.HillockTransportation, RewardValue.Low, resources.HillockTransportationTooltip),
Fortification = new BetrayalReward(resources.HillockFortification, RewardValue.Low, resources.HillockFortificationTooltip),
Research = new BetrayalReward(resources.HillockResearch, RewardValue.Low, resources.HillockResearchTooltip),
Intervention = new BetrayalReward(resources.HillockIntervention, RewardValue.NoValue, resources.HillockInterventionTooltip)
});
agents.Add(new BetrayalAgent(resources.ItThatFledName, "It_That_Fled.png", RewardValue.High)
{
Transportation = new BetrayalReward(resources.ItThatFledTransportation, RewardValue.Low),
Fortification = new BetrayalReward(resources.ItThatFledFortification, RewardValue.Low),
Research = new BetrayalReward(resources.ItThatFledResearch, RewardValue.High, resources.ItThatFledResearchTooltip),
Intervention = new BetrayalReward(resources.ItThatFledIntervention, RewardValue.Low)
});
agents.Add(new BetrayalAgent(resources.JreplacedName, "Jreplaced.png", RewardValue.Low)
{
Transportation = new BetrayalReward(resources.JreplacedTransportation, RewardValue.Low),
Fortification = new BetrayalReward(resources.JreplacedFortification, RewardValue.Low),
Research = new BetrayalReward(resources.JreplacedResearch, RewardValue.Low),
Intervention = new BetrayalReward(resources.JreplacedIntervention, RewardValue.Low)
});
agents.Add(new BetrayalAgent(resources.JorginName, "Jorgin.png", RewardValue.Medium)
{
Transportation = new BetrayalReward(resources.JorginTransportation, RewardValue.Low),
Fortification = new BetrayalReward(resources.JorginFortification, RewardValue.Medium),
Research = new BetrayalReward(resources.JorginResearch, RewardValue.Medium, resources.JorginResearchTooltip),
Intervention = new BetrayalReward(resources.JorginIntervention, RewardValue.Low)
});
agents.Add(new BetrayalAgent(resources.KorellName, "Korell.png", RewardValue.Medium)
{
Transportation = new BetrayalReward(resources.KorellTransportation, RewardValue.Low),
Fortification = new BetrayalReward(resources.KorellFortification, RewardValue.Medium),
Research = new BetrayalReward(resources.KorellResearch, RewardValue.Medium),
Intervention = new BetrayalReward(resources.KorellIntervention, RewardValue.Low)
});
agents.Add(new BetrayalAgent(resources.LeoName, "Leo.png", RewardValue.Medium)
{
Transportation = new BetrayalReward(resources.LeoTransportation, RewardValue.Low),
Fortification = new BetrayalReward(resources.LeoFortification, RewardValue.Medium),
Research = new BetrayalReward(resources.LeoResearch, RewardValue.Medium, resources.LeoResearchTooltip),
Intervention = new BetrayalReward(resources.LeoIntervention, RewardValue.Low)
});
agents.Add(new BetrayalAgent(resources.RikerName, "Riker.png", RewardValue.Medium)
{
Transportation = new BetrayalReward(resources.RikerTransportation, RewardValue.Medium),
Fortification = new BetrayalReward(resources.RikerFortification, RewardValue.Low),
Research = new BetrayalReward(resources.RikerResearch, RewardValue.NoValue),
Intervention = new BetrayalReward(resources.RikerIntervention, RewardValue.Medium)
});
agents.Add(new BetrayalAgent(resources.RinName, "Rin.png", RewardValue.High)
{
Transportation = new BetrayalReward(resources.RinTransportation, RewardValue.Low),
Fortification = new BetrayalReward(resources.RinFortification, RewardValue.Low),
Research = new BetrayalReward(resources.RinResearch, RewardValue.Low),
Intervention = new BetrayalReward(resources.RinIntervention, RewardValue.High)
});
agents.Add(new BetrayalAgent(resources.ToraName, "Tora.png", RewardValue.High)
{
Transportation = new BetrayalReward(resources.ToraTransportation, RewardValue.Medium, resources.ToraTransportationTooltip),
Fortification = new BetrayalReward(resources.ToraFortification, RewardValue.Low, resources.ToraFortificationTooltip),
Research = new BetrayalReward(resources.ToraResearch, RewardValue.High, resources.ToraResearchTooltip),
Intervention = new BetrayalReward(resources.ToraIntervention, RewardValue.Low)
});
agents.Add(new BetrayalAgent(resources.VaganName, "Vagan.png", RewardValue.Medium)
{
Transportation = new BetrayalReward(resources.VaganTransportation, RewardValue.Medium),
Fortification = new BetrayalReward(resources.VaganFortification, RewardValue.Medium),
Research = new BetrayalReward(resources.VaganResearch, RewardValue.Medium),
Intervention = new BetrayalReward(resources.VaganIntervention, RewardValue.Medium)
});
agents.Add(new BetrayalAgent(resources.VoriciName, "Vorici.png", RewardValue.High)
{
Transportation = new BetrayalReward(resources.VoriciTransportation, RewardValue.Low),
Fortification = new BetrayalReward(resources.VoriciFortification, RewardValue.Medium),
Research = new BetrayalReward(resources.VoriciResearch, RewardValue.High, resources.VoriciResearchTooltip),
Intervention = new BetrayalReward(resources.VoriciIntervention, RewardValue.Low)
});
switch (settings.Cheatsheets_Betrayal_Sort)
{
case "":
agents = agents.OrderBy(x => x.Name).ToList();
break;
case "value":
agents = agents.OrderByDescending(x => GetRewardValue(x.Fortification) + GetRewardValue(x.Transportation) + GetRewardValue(x.Research) + GetRewardValue(x.Intervention)).ThenBy(x => x.Name).ToList();
break;
case "transportation":
agents = agents.OrderByDescending(x => GetRewardValue(x.Transportation)).ThenBy(x => x.Name).ToList();
break;
case "fortification":
agents = agents.OrderByDescending(x => GetRewardValue(x.Fortification)).ThenBy(x => x.Name).ToList();
break;
case "research":
agents = agents.OrderByDescending(x => GetRewardValue(x.Research)).ThenBy(x => x.Name).ToList();
break;
case "intervention":
agents = agents.OrderByDescending(x => GetRewardValue(x.Intervention)).ThenBy(x => x.Name).ToList();
break;
}
return Task.FromResult(new BetrayalLeague()
{
Agents = agents
});
}
19
Source : ChallengeEvaluation.cs
with MIT License
from dotnet-interactive-learning
with MIT License
from dotnet-interactive-learning
private PocketView FormatAsHtml()
{
var elements = new List<PocketView>();
var succeededRules = ruleEvaluations.Values.Count(r => r.Outcome == Outcome.Success);
var totalRules = ruleEvaluations.Count;
var countReport = totalRules > 0 ? $"({succeededRules}/{totalRules})" : string.Empty;
var message = string.IsNullOrWhiteSpace(Message) ? $"{countReport} rules have preplaceded." : Message;
if (string.IsNullOrWhiteSpace(label))
{
PocketView header = summary[@clreplaced: "challengeSummary"](b(message));
elements.Add(header);
}
else
{
PocketView header = summary[@clreplaced: "challengeSummary"](($"[ {this.label} ]: "), b(message));
elements.Add(header);
}
if (Hint is not null)
{
var hintElement = div[@clreplaced: "challengeHint"](Hint.ToDisplayString(HtmlFormatter.MimeType).ToHtmlContent());
elements.Add(hintElement);
}
foreach (var rule in ruleEvaluations.Values.OrderBy(r => r.Outcome).ThenBy(r => r.Name))
{
elements.Add(div[@clreplaced: "ruleContainer"](rule.ToDisplayString(HtmlFormatter.MimeType).ToHtmlContent()));
}
PocketView report = details[@clreplaced: "challengeEvaluation", open: "true"](elements);
return report;
}
19
Source : AssemblerOutputToolWindowViewModel.cs
with MIT License
from Dotneteer
with MIT License
from Dotneteer
private void RefreshFixups()
{
ToggleFixupCommandText = FilterToUnresolvedFixups
? "Show all fixups"
: "Show unresolved fixups";
if (Output == null) return;
IEnumerable<FixupEntry> fixups = Output.Fixups;
if (FilterToUnresolvedFixups)
{
fixups = Output.Fixups.Where(fu => !fu.Resolved);
}
var fixupInfo = fixups.OrderBy(fu => fu.SegmentIndex)
.ThenBy(fu => fu.Offset)
.Select(fu => new FixupInfo(fu.Type,
fu.SegmentIndex,
(ushort)fu.Offset,
fu.Resolved,
fu.Type == FixupType.Equ
? fu.Label
: fu.Expression?.SourceText
));
Fixups = new ObservableCollection<FixupInfo>(fixupInfo);
}
19
Source : SpeakersViewModel.cs
with MIT License
from DotNetRu
with MIT License
from DotNetRu
private void SortSpeakers(IEnumerable<SpeakerModel> speakers)
{
var speakersSorted = speakers.Select(speaker => new { speaker, firstChar = Char.ToUpperInvariant(speaker.FullName[0])})
.OrderBy(s => 'A' <= s.firstChar && s.firstChar <= 'Z') //english names in the bottom
.ThenBy(s => s.speaker.FullName)
.GroupBy(s => s.firstChar)
.Select(g => new Grouping<char, SpeakerModel>(g.Key, g.Select(s => s.speaker)));
this.speakers.ReplaceRange(speakersSorted);
}
19
Source : GrabbedMediaExtensions.cs
with GNU Lesser General Public License v3.0
from dotnettools
with GNU Lesser General Public License v3.0
from dotnettools
public static IOrderedEnumerable<GrabbedMedia> ThenByResolution(this IOrderedEnumerable<GrabbedMedia> grabbed)
{
return grabbed.ThenBy(m => m.GetResolutionDescriptor());
}
19
Source : GrabbedMediaExtensions.cs
with GNU Lesser General Public License v3.0
from dotnettools
with GNU Lesser General Public License v3.0
from dotnettools
public static IOrderedEnumerable<GrabbedMedia> ThenByBitRate(this IOrderedEnumerable<GrabbedMedia> grabbed)
{
return grabbed.ThenBy(m => m.GetBitRate());
}
19
Source : MultiColumnTreeView.cs
with MIT License
from dshook
with MIT License
from dshook
public static IOrderedEnumerable<T> ThenBy<T, TKey>(this IOrderedEnumerable<T> source, Func<T, TKey> selector, bool ascending)
{
if (ascending)
{
return source.ThenBy(selector);
}
else
{
return source.ThenByDescending(selector);
}
}
19
Source : RouterModule.cs
with MIT License
from duyanming
with MIT License
from duyanming
[AnnoInfo(Desc = "获取服务路由信息")]
public ActionResult GetRoutingInfo([AnnoInfo(Desc = "服务名称")] string appName)
{
Dictionary<string, string> input = new Dictionary<string, string>();
input.Add(StorageCommand.COMMAND, StorageCommand.APIDOCCOMMAND);
input.Add(CONST.Opt, CONST.FindByApp);
input.Add(CONST.App, appName);
string rlt = StorageEngine.Invoke(input);
List<AnnoDataOutPut> annoDataOutPuts = new List<AnnoDataOutPut>();
RoutingInfomationDto routing = Newtonsoft.Json.JsonConvert.DeserializeObject<RoutingInfomationDto>(rlt);
if (routing.Data != null && routing.Data.Count > 0)
{
routing.Data.ForEach(d =>
{
annoDataOutPuts.Add(new AnnoDataOutPut()
{
App = d.App,
Channel = d.Channel,
Router = d.Router,
Method = d.Method,
Desc = d.ValueObj.Desc,
Value = d.ValueObj
});
});
}
return new ActionResult(true, annoDataOutPuts.OrderBy(d => d.Channel).ThenBy(d => d.Router).ThenBy(d => d.Method));
}
19
Source : AssetsMetadata.cs
with MIT License
from emulamer
with MIT License
from emulamer
public void Parse(replacedetsReader reader)
{
Version = reader.ReadCStr();
Platform = reader.ReadInt32();
HasTypeTrees = reader.ReadBoolean();
int numTypes = reader.ReadInt32();
for (int i = 0; i < numTypes; i++)
{
Types.Add(new replacedetsType(reader, HasTypeTrees));
}
List<ObjectRecord> records = new List<ObjectRecord>();
int numObj = reader.ReadInt32();
for (int i = 0; i < numObj; i++)
{
reader.AlignTo(4);
var obj = new ObjectRecord(reader);
records.Add(obj);
}
int numAdds = reader.ReadInt32();
for (int i = 0; i < numAdds; i++)
{
reader.AlignTo(4);
Adds.Add(new RawPtr(reader));
}
int numExt = reader.ReadInt32();
for (int i = 0; i < numExt; i++)
{
ExternalFiles.Add(new ExternalFile(reader));
}
reader.ReadCStr();
//load the object infos in order based on their type
foreach (var record in records.OrderBy(x=> PreloadObjectOrder(x)).ThenBy(x=> x.ObjectID))
{
var obj = ObjectInfo<replacedetsObject>.Parse(ParentFile, record);
ObjectInfos.Add(obj);
if (ShouldForceLoadObject(record))
{
var o = obj.Object;
}
}
}
19
Source : Mft.cs
with MIT License
from EricZimmerman
with MIT License
from EricZimmerman
public List<ParentMapEntry> GetDirectoryContents(string key)
{
if (_parentDirectoryNameMap.ContainsKey(key))
{
return _parentDirectoryNameMap[key].OrderByDescending(t=>t.IsDirectory).ThenBy(t=>t.FileName).ToList();
}
return new List<ParentMapEntry>();
}
19
Source : RecentDocs.cs
with MIT License
from EricZimmerman
with MIT License
from EricZimmerman
private IEnumerable<RecentDoc> ProcessRecentKey(RegistryKey key)
{
var l = new List<RecentDoc>();
try
{
var mruList = key.Values.SingleOrDefault(t => t.ValueName == "MRUListEx");
var mruPositions = new Dictionary<uint, int>();
var index = 0;
if (mruList != null)
{
var i = 0;
var mruPos = BitConverter.ToUInt32(mruList.ValueDataRaw, index);
index += 4;
while (mruPos != 0xFFFFFFFF)
{
mruPositions.Add(mruPos, i);
i++;
mruPos = BitConverter.ToUInt32(mruList.ValueDataRaw, index);
index += 4;
}
//mruPositions now contains a map of positions (the key) to the order it was opened (the value)
}
foreach (var keyValue in key.Values)
{
if (keyValue.ValueName == "MRUListEx" || keyValue.ValueName == "ViewStream")
{
continue;
}
var mru = mruPositions[uint.Parse(keyValue.ValueName)];
var targetName = Encoding.Unicode.GetString(keyValue.ValueDataRaw).Split('\0')[0];
var offsetToRemainingData = targetName.Length * 2 + 2;
//TODO do not use Skip. use Buffer.BlockCopy as its faster
var remainingData = keyValue.ValueDataRaw.Skip(offsetToRemainingData).ToArray();
index = 0;
var chunkLen = BitConverter.ToUInt16(remainingData, index);
var chunks = new List<byte[]>();
while (remainingData.Length > index)
{
var chunk = remainingData.Skip(index).Take(chunkLen).ToArray();
chunks.Add(chunk);
index += chunkLen;
chunkLen = BitConverter.ToUInt16(remainingData, index);
if (chunkLen == 0)
{
break;
}
}
index = 2; //skip chunk length
var lnkNameType = chunks[0][index]; // if 32, its unicode, if 36, ascii
index += 12; //skip type that always seems to be [32|36]-00-00-00-00-00-00-00-00-00-00-00-
var lnkName = "";
if (lnkNameType == 36)
{
lnkName = Encoding.Unicode.GetString(chunks[0].Skip(index).ToArray()).Split('\0')[0];
index += lnkName.Length * 2;
}
else
{
lnkName = Encoding.GetEncoding(1252).GetString(chunks[0].Skip(index).ToArray()).Split('\0')[0];
index += lnkName.Length;
}
while (chunks[0][index] != 4)
{
index += 1; //move until our signature
}
index -= 4; //jump back to start of extension block
var beefBytes = chunks[0].Skip(index).ToArray();
var sig = BitConverter.ToUInt32(beefBytes, 4);
var beef = (Beef0004) Utils.GetExtensionBlockFromBytes(sig, beefBytes);
DateTimeOffset? openedOn = null;
if (mru == 0)
{
openedOn = key.LastWriteTime;
}
DateTimeOffset? extLastOpened = null;
var ext = Path.GetExtension(targetName).ToLowerInvariant();
var targetName1 = string.Empty;
if (ext.Length == 0)
{
//folder
var sk1 = key.SubKeys.SingleOrDefault(t => t.KeyName == "Folder");
var skmru = sk1?.Values.SingleOrDefault(t => t.ValueName == "MRUListEx");
if (skmru != null)
{
//get last accessed folder value name
var mruPosf = BitConverter.ToInt32(skmru.ValueDataRaw, 0);
//pull folder name from the value
var val1 = sk1.Values.SingleOrDefault(t => t.ValueName == mruPosf.ToString());
targetName1 = Encoding.Unicode.GetString(val1.ValueDataRaw).Split('\0')[0];
}
if (sk1 != null && targetName1 == targetName)
{
extLastOpened = sk1.LastWriteTime;
}
}
else
{
var sk2 = key.SubKeys.SingleOrDefault(t => t.KeyName.ToLowerInvariant() == ext);
var skmruf = sk2?.Values.SingleOrDefault(t => t.ValueName == "MRUListEx");
if (skmruf != null)
{
//get last accessed folder value name
var mruPosff = BitConverter.ToInt32(skmruf.ValueDataRaw, 0);
//pull folder name from the value
var val1 = sk2.Values.SingleOrDefault(t => t.ValueName == mruPosff.ToString());
targetName1 = Encoding.Unicode.GetString(val1.ValueDataRaw).Split('\0')[0];
}
if (sk2 != null && targetName1 == targetName)
{
extLastOpened = sk2.LastWriteTime;
}
}
var rd = new RecentDoc(mru, keyValue.ValueName, targetName, beef.LongName, key.KeyName, openedOn, extLastOpened);
rd.BatchKeyPath = key.KeyPath;
rd.BatchValueName = keyValue.ValueName;
l.Add(rd);
}
}
catch (Exception ex)
{
Errors.Add($"Error processing recent key ({key.KeyPath}): {ex.Message}");
}
foreach (var registryKey in key.SubKeys)
{
var subItems = ProcessRecentKey(registryKey);
l.AddRange(subItems);
}
if (Errors.Count > 0)
{
AlertMessage = "Errors detected. See Errors information in lower right corner of plugin window";
}
l = l.OrderByDescending(t => t.Extension).ThenBy(t => t.MruPosition).ToList();
return l;
}
19
Source : DefaultTypeMap.cs
with MIT License
from eznew-net
with MIT License
from eznew-net
public ConstructorInfo FindConstructor(string[] names, Type[] types)
{
var constructors = _type.GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
foreach (ConstructorInfo ctor in constructors.OrderBy(c => c.IsPublic ? 0 : (c.IsPrivate ? 2 : 1)).ThenBy(c => c.GetParameters().Length))
{
ParameterInfo[] ctorParameters = ctor.GetParameters();
if (ctorParameters.Length == 0)
return ctor;
if (ctorParameters.Length != types.Length)
continue;
int i = 0;
for (; i < ctorParameters.Length; i++)
{
if (!string.Equals(ctorParameters[i].Name, names[i], StringComparison.OrdinalIgnoreCase))
break;
if (types[i] == typeof(byte[]) && ctorParameters[i].ParameterType.FullName == SqlMapper.LinqBinary)
continue;
var unboxedType = Nullable.GetUnderlyingType(ctorParameters[i].ParameterType) ?? ctorParameters[i].ParameterType;
if ((unboxedType != types[i] && !SqlMapper.HasTypeHandler(unboxedType))
&& !(unboxedType.IsEnum && Enum.GetUnderlyingType(unboxedType) == types[i])
&& !(unboxedType == typeof(char) && types[i] == typeof(string))
&& !(unboxedType.IsEnum && types[i] == typeof(string)))
{
break;
}
}
if (i == ctorParameters.Length)
return ctor;
}
return null;
}
19
Source : PredictionView.cs
with MIT License
from fatheroctopus
with MIT License
from fatheroctopus
private void TestView()
{
var cardList = new List<PredictionInfo.CardInfo>();
for (int n = 0; n < 2; n++)
{
var card0 = Database.GetCardFromName("Ice Block");
card0.Count = 3;
var cardInfo0 = new PredictionInfo.CardInfo(card0, 0); // OffMeta, Unplayed
var card1 = Database.GetCardFromName("Ice Block");
var cardInfo1 = new PredictionInfo.CardInfo(card1, 1); // OffMeta, Played
var card2 = Database.GetCardFromName("Ice Block");
card2.Count = 2;
var cardInfo2 = new PredictionInfo.CardInfo(card2, new List<decimal> {1, 1}, 0); // Unplayed
var card3 = Database.GetCardFromName("Ice Block");
card3.IsCreated = true;
var cardInfo3 = new PredictionInfo.CardInfo(card3, 1); // Created and Played
var card4 = Database.GetCardFromName("Cryomancer");
var cardInfo4 = new PredictionInfo.CardInfo(card4, new List<decimal> {1, 1}, 0);
var card5 = Database.GetCardFromName("Polymorph");
var cardInfo5 = new PredictionInfo.CardInfo(card5, new List<decimal> {.5m, 1}, 0);
cardList.Add(cardInfo0);
cardList.Add(cardInfo1);
cardList.Add(cardInfo2);
cardList.Add(cardInfo3);
cardList.Add(cardInfo4);
cardList.Add(cardInfo5);
}
cardList = cardList
.OrderBy(cardInfo => cardInfo.Card.Cost)
.ThenBy(cardInfo => cardInfo.Card.Name)
.ToList();
var prediction = new PredictionInfo(1, 30, 4, 5, cardList, new List<PredictionInfo.CardInfo> {});
SetEnabled(true);
OnPredictionUpdate(prediction);
}
19
Source : Predictor.cs
with MIT License
from fatheroctopus
with MIT License
from fatheroctopus
private void UpdatePredictedCards()
{
// Determine which cards are possible.
_possibleCards.Clear();
foreach (Deck deck in _possibleDecks)
{
foreach (Card card in deck.Cards)
{
for (int copyCount = 1; copyCount <= card.Count; copyCount++)
{
var key = CardInfo.Key(card, copyCount);
if (!_possibleCards.ContainsKey(key))
{
var predictedCard = new CardInfo(card, copyCount, _possibleDecks.Count);
_possibleCards[key] = predictedCard;
}
_possibleCards[key].IncrementNumOccurrences();
}
}
}
// Prediction
// First sort possible cards by probability
var sortedPossibleCards = _possibleCards.Values
.OrderByDescending(predictedCard => predictedCard.Probability)
.ThenBy(predictedCard => predictedCard.Card.Cost)
.ThenBy(predictedCard => predictedCard.Card.Name)
.ToList();
// If our list is greater than the PredictionSize, find the probability of the first card that
// won't make the cut. All other cards have to be strictly greater than that probability.
// We do this so none of the top 30 are there for an arbitrary reason.
decimal insufficientProbability = sortedPossibleCards.Count > PredictionSize
? sortedPossibleCards.ElementAt(PredictionSize).Probability
: 0;
_predictedCards = sortedPossibleCards
.TakeWhile(predictedCard => predictedCard.Probability > insufficientProbability &&
predictedCard.Probability >= ProbabilityAlwaysInclude)
.ToList();
// Now go through the remaining possible cards to fill out the deck with speculative picks.
decimal lastPickProbability = 1;
_nextPredictedCards = new List<CardInfo>();
sortedPossibleCards.Skip(_predictedCards.Count).ToList().ForEach(possibleCard =>
{
// A speculative card is only added if its probability is high enough and it preplacedes
// the check based on the opponent's available mana.
// Cards are playable if they are less than or equal to available mana.
// Cards are optimal if they are equal to available mana with and without the coin.
bool isPlayable = possibleCard.Card.Cost <= AvailableManaWithCoin;
bool playableCheck = isPlayable &&
possibleCard.Probability >= ProbabilityIncludeIfPlayable;
bool isOptimal = (possibleCard.Card.Cost == AvailableMana ||
possibleCard.Card.Cost == AvailableManaWithCoin);
bool optimalCheck = isOptimal &&
possibleCard.Probability >= ProbabilityIncludeIfOptimal;
// Go until the deck is filled, but allow in all valid cards at the same probability.
if ((playableCheck || optimalCheck) &&
(_predictedCards.Count < PredictionSize ||
possibleCard.Probability >= lastPickProbability))
{
_predictedCards.Add(possibleCard);
lastPickProbability = possibleCard.Probability;
}
else
{
_nextPredictedCards.Add(possibleCard);
}
});
_predictedCards = _predictedCards
.OrderBy(predictedCard => predictedCard.Card.Cost)
.ThenBy(predictedCard => predictedCard.Card.Name)
.ToList();
Log.Debug("Target prediction size: " + PredictionSize);
Log.Debug(_possibleCards.Count + " possible cards");
Log.Debug(_predictedCards.Count + " predicted cards");
}
19
Source : D3.cs
with MIT License
from fel88
with MIT License
from fel88
public static double[][] polygonHull(double[][] points)
{
int n;
n = points.Count();
if ((n) < 3) return null;
HullInfoPoint[] sortedPoints = new HullInfoPoint[n];
double[][] flippedPoints = new double[n][];
for (int i = 0; i < n; ++i) sortedPoints[i] = new HullInfoPoint { x = points[i][0], y = points[i][1], index = i };
sortedPoints = sortedPoints.OrderBy(x => x.x).ThenBy(z => z.y).ToArray();
for (int i = 0; i < n; ++i) flippedPoints[i] = new double[] { sortedPoints[i].x, -sortedPoints[i].y };
var upperIndexes = computeUpperHullIndexes(sortedPoints.Select(z => new double[] { z.x, z.y, z.index }).ToArray());
var lowerIndexes = computeUpperHullIndexes(flippedPoints);
// Construct the hull polygon, removing possible duplicate endpoints.
var skipLeft = lowerIndexes[0] == upperIndexes[0];
var skipRight = lowerIndexes[lowerIndexes.Length - 1] == upperIndexes[upperIndexes.Length - 1];
List<double[]> hull = new List<double[]>();
// Add upper hull in right-to-l order.
// Then add lower hull in left-to-right order.
for (int i = upperIndexes.Length - 1; i >= 0; --i)
hull.Add(points[sortedPoints[upperIndexes[i]].index]);
//for (int i = +skipLeft; i < lowerIndexes.Length - skipRight; ++i) hull.push(points[sortedPoints[lowerIndexes[i]][2]]);
for (int i = skipLeft ? 1 : 0; i < lowerIndexes.Length - (skipRight ? 1 : 0); ++i) hull.Add(points[sortedPoints[lowerIndexes[i]].index]);
return hull.ToArray();
}
19
Source : CmsColumnService.cs
with MIT License
from feiyit
with MIT License
from feiyit
private void ChildModule(List<CmsColumn> list, List<CmsColumn> newlist, int parentId)
{
var result = list.Where(p => p.ParentId == parentId).OrderBy(p => p.ClreplacedLayer).ThenBy(p => p.Sort).ToList();
if (result.Any())
{
for (int i = 0; i < result.Count(); i++)
{
newlist.Add(result[i]);
ChildModule(list, newlist, result[i].Id);
}
}
}
19
Source : SysMenuService.cs
with MIT License
from feiyit
with MIT License
from feiyit
private void ChildModule(List<SysMenu> list, List<SysMenu> newlist, string parentId)
{
var result = list.Where(p => p.ParentGuid == parentId).OrderBy(p => p.Layer).ThenBy(p => p.Sort).ToList();
if (!result.Any()) return;
for (int i = 0; i < result.Count(); i++)
{
newlist.Add(result[i]);
ChildModule(list, newlist, result[i].Guid);
}
}
19
Source : DuplicateHiderSettings.cs
with MIT License
from felixkmh
with MIT License
from felixkmh
public void BeginEdit()
{
// Code executed when settings view is opened and user starts editing values.
previousSettings = this.Copy();
plugin.SettingsView.Dispatcher.Invoke(() =>
{
plugin.SettingsView.GroupsList.DataContext = new CustomGroupsViewModel(CustomGroups) { Synchronize = false };
plugin.SettingsView.AutoUpdateCheckBox.IsChecked = UpdateAutomatically;
plugin.SettingsView.ShowCopiesInGameMenu.IsChecked = ShowOtherCopiesInGameMenu;
plugin.SettingsView.AddHiddenToIgnoreList.IsChecked = AddHiddenToIgnoreList;
plugin.SettingsView.PrioritizeNewerGame.IsChecked = PreferNewerGame;
// Populate Replacement Rules
{
foreach (var filter in ReplaceFilters)
{
if (filter is ReplaceFilter rf)
{
plugin.SettingsView.ReplacementRulesListBox.Items.Add(
CreateReplacementFilterItem(rf)
);
}
}
plugin.SettingsView.ReplacementRulesListBox.Items.Add(
CreateReplacementFilterItem()
);
}
// Populate Priority list
{
plugin.SettingsView.PriorityListBox.Items.Clear();
// Add missing sources to the end of the Priority list
foreach (var source in plugin.PlayniteApi.Database.Sources)
{
Priorities.AddMissing(source.Name);
}
Priorities.AddMissing(Constants.UNDEFINED_SOURCE);
// Add valid entries to the PriorityListBox
foreach (var sourceName in Priorities)
{
if (plugin.PlayniteApi.Database.Sources.TryFind(s => s.Name == sourceName, out var source))
{
plugin.SettingsView.PriorityListBox.Items.Add(plugin.SettingsView.CreatePriorityEntry(source));
}
else if (sourceName == Constants.UNDEFINED_SOURCE)
{
plugin.SettingsView.PriorityListBox.Items.Add(plugin.SettingsView.CreatePriorityEntry(null));
}
}
}
// Populate PlatformComboBox
{
List<CheckBox> checkBoxes = new List<CheckBox>();
foreach (var platform in plugin.PlayniteApi.Database.Platforms.Concat(new List<Platform> { null }))
{
string platformName = platform != null ? platform.Name : Constants.UNDEFINED_PLATFORM;
var cb = new CheckBox { Content = platformName, Tag = platform };
cb.IsChecked = IncludePlatforms.Contains(platformName);
checkBoxes.Add(cb);
}
checkBoxes = checkBoxes.OrderByDescending(cb => cb.IsChecked).ThenBy(cb => cb.Content).ToList();
plugin.SettingsView.Platforms = checkBoxes;
checkBoxes.ForEach(cb => plugin.SettingsView.PlatformComboBox.Items.Add(cb));
}
// Populate SourceComboBox
{
List<CheckBox> checkBoxes = new List<CheckBox>();
foreach (var source in plugin.PlayniteApi.Database.Sources.Concat(new List<GameSource> { null }))
{
string sourceName = source != null ? source.Name : Constants.UNDEFINED_SOURCE;
var cb = new CheckBox { Content = sourceName, Tag = source };
cb.IsChecked = ExcludeSources.Contains(sourceName);
checkBoxes.Add(cb);
}
checkBoxes = checkBoxes.OrderByDescending(cb => cb.IsChecked).ThenBy(cb => cb.Content).ToList();
plugin.SettingsView.Sources = checkBoxes;
checkBoxes.ForEach(cb => plugin.SettingsView.SourceComboBox.Items.Add(cb));
}
// Populate CategoriesComboBox
{
List<CheckBox> checkBoxes = new List<CheckBox>();
foreach (var category in plugin.PlayniteApi.Database.Categories)
{
var cb = new CheckBox { Content = category.Name, Tag = category };
cb.IsChecked = ExcludeCategories.Contains(category.Name);
checkBoxes.Add(cb);
}
checkBoxes = checkBoxes.OrderByDescending(cb => cb.IsChecked).ThenBy(cb => cb.Content).ToList();
plugin.SettingsView.Categories = checkBoxes;
checkBoxes.ForEach(cb => plugin.SettingsView.CategoriesComboBox.Items.Add(cb));
}
// Populate IgnoredGames ListBox
{
plugin.SettingsView.IgnoreListBox.Items.Clear();
foreach (var id in IgnoredGames)
{
var item = new ListBoxItem
{
Tag = id,
ContextMenu = new ContextMenu()
};
var menuItem = new MenuItem { Header = "Remove Entry", Tag = id };
menuItem.Click += RemoveIgnored_Click;
item.ContextMenu.Items.Add(menuItem);
var game = plugin.PlayniteApi.Database.Games.Get(id);
item.Content = game == null ? "Game not found: " + id.ToString() : $"{game.Name} ({game.GetSourceName()})";
item.ToolTip = item.Content;
plugin.SettingsView.IgnoreListBox.Items.Add(item);
}
}
// Add context menu options to FormatString TextField
{
var textBox = plugin.SettingsView.DisplayStringTextBox;
textBox.Text = DisplayString ?? "";
var contextMenu = textBox.ContextMenu = new ContextMenu();
foreach (var variable in DuplicateHiderPlugin.GetGameVariables())
{
var item = new MenuItem
{
Header = variable.Key
};
item.Click += InsertVariable;
item.Tag = variable.Value;
contextMenu.Items.Add(item);
}
}
// Populate UI Integration Settings
{
plugin.SettingsView.EnableThemeIconsChechBox.IsChecked = EnableThemeIcons;
plugin.SettingsView.UiIntegrationCheckBox.IsChecked = EnableUiIntegration;
plugin.SettingsView.PreferUserIconsCheckBox.IsChecked = PreferUserIcons;
plugin.SettingsView.ShowSingleSourceIconCheckBox.IsChecked = ShowSingleIcon;
plugin.SettingsView.OpenUserIconFolderButton.Click += (_, __) => System.Diagnostics.Process.Start("explorer.exe", plugin.GetUserIconFolderPath());
plugin.SettingsView.SuppressNotificationCheckBox.IsChecked = SupressThemeIconNotification;
}
});
}
19
Source : DuplicateHiderSettingsView.xaml.cs
with MIT License
from felixkmh
with MIT License
from felixkmh
private void CategoriesComboBox_DropDownClosed(object sender, EventArgs e)
{
if (sender is ComboBox comboBox)
{
comboBox.Items.Clear();
foreach (var checkbox in Categories.OrderByDescending(cb => cb.IsChecked).ThenBy(o => (string)o.Content))
{
bool found = ((string)checkbox.Content).ToLower().Contains(comboBox.Text.ToLower());
if (string.IsNullOrEmpty(comboBox.Text) || found)
{
comboBox.Items.Add(checkbox);
}
}
}
}
19
Source : DuplicateHiderSettingsView.xaml.cs
with MIT License
from felixkmh
with MIT License
from felixkmh
private void PlatformComboBox_PreviewKeyUp(object sender, KeyEventArgs e)
{
if (sender is ComboBox comboBox)
{
comboBox.Items.Clear();
foreach (var checkbox in Platforms.OrderByDescending(cb => cb.IsChecked).ThenBy(cb => (string)cb.Content))
{
bool found = ((string)checkbox.Content).ToLower().Contains(comboBox.Text.ToLower());
if (string.IsNullOrEmpty(comboBox.Text) || found)
{
comboBox.Items.Add(checkbox);
}
}
comboBox.IsDropDownOpen = true;
}
}
19
Source : DuplicateHiderSettingsView.xaml.cs
with MIT License
from felixkmh
with MIT License
from felixkmh
private void SourceComboBox_PreviewKeyUp(object sender, KeyEventArgs e)
{
if (sender is ComboBox comboBox)
{
comboBox.Items.Clear();
foreach (var checkbox in Sources.OrderByDescending(cb => cb.IsChecked).ThenBy(o => (string)o.Content))
{
bool found = ((string)checkbox.Content).ToLower().Contains(comboBox.Text.ToLower());
if (string.IsNullOrEmpty(comboBox.Text) || found)
{
comboBox.Items.Add(checkbox);
}
}
comboBox.IsDropDownOpen = true;
}
}
19
Source : CommandHistoryService.cs
with GNU General Public License v3.0
from felixse
with GNU General Public License v3.0
from felixse
public void MarkUsed(ShellProfile profile)
{
var history = GetRawHistory();
var existing = history.FirstOrDefault(c =>
c.ProfileId?.Equals(profile.Id) ??
string.Equals(profile.Name, c.Value, StringComparison.OrdinalIgnoreCase));
if (existing == null)
{
if (string.IsNullOrEmpty(profile.Name))
{
profile.Name = $"{profile.Location} {profile.Arguments}".Trim();
}
existing = new ExecutedCommand {Value = profile.Name};
if (_settingsService.GetAllProfiles().Any(p => p.Id.Equals(profile.Id)))
{
existing.ProfileId = profile.Id;
}
else
{
existing.ShellProfile = profile;
}
var overflow = history.Count - MaxHistory + 1;
if (overflow > 0)
{
// We already have max number of commands in history, so we need to delete some
// Let's first try with cleanup
CleanupHistory();
overflow = history.Count - MaxHistory + 1;
if (overflow > 0)
{
// We will remove the oldest commands
var toRemove = history.OrderBy(c => c.LastExecution).ThenBy(c => c.ExecutionCount)
.Take(overflow).ToList();
foreach (var command in toRemove)
{
history.Remove(command);
Delete(command);
}
}
}
history.Add(existing);
}
else if (existing.ShellProfile != null)
{
existing.ShellProfile = profile;
}
existing.LastExecution = DateTime.UtcNow;
existing.ExecutionCount++;
Save(existing);
}
19
Source : DuplicateHiderSettingsView.xaml.cs
with MIT License
from felixkmh
with MIT License
from felixkmh
private void CategoriesComboBox_PreviewKeyUp(object sender, KeyEventArgs e)
{
if (sender is ComboBox comboBox)
{
comboBox.Items.Clear();
foreach (var checkbox in Categories.OrderByDescending(cb => cb.IsChecked).ThenBy(o => (string)o.Content))
{
bool found = ((string)checkbox.Content).ToLower().Contains(comboBox.Text.ToLower());
if (string.IsNullOrEmpty(comboBox.Text) || found)
{
comboBox.Items.Add(checkbox);
}
}
comboBox.IsDropDownOpen = true;
}
}
19
Source : DuplicateHiderSettingsView.xaml.cs
with MIT License
from felixkmh
with MIT License
from felixkmh
private void PlatformComboBox_DropDownClosed(object sender, EventArgs e)
{
if (sender is ComboBox comboBox)
{
comboBox.Items.Clear();
foreach (var checkbox in Platforms.OrderByDescending(cb => cb.IsChecked).ThenBy(o => (string)o.Content))
{
bool found = ((string)checkbox.Content).ToLower().Contains(comboBox.Text.ToLower());
if (string.IsNullOrEmpty(comboBox.Text) || found)
{
comboBox.Items.Add(checkbox);
}
}
}
}
19
Source : DuplicateHiderSettingsView.xaml.cs
with MIT License
from felixkmh
with MIT License
from felixkmh
private void SourceComboBox_DropDownClosed(object sender, EventArgs e)
{
if (sender is ComboBox comboBox)
{
comboBox.Items.Clear();
foreach (var checkbox in Sources.OrderByDescending(cb => cb.IsChecked).ThenBy(o => (string)o.Content))
{
bool found = ((string)checkbox.Content).ToLower().Contains(comboBox.Text.ToLower());
if (string.IsNullOrEmpty(comboBox.Text) || found)
{
comboBox.Items.Add(checkbox);
}
}
}
}
19
Source : SortingHelper.cs
with GNU General Public License v3.0
from files-community
with GNU General Public License v3.0
from files-community
public static IEnumerable<ListedItem> OrderFileList(List<ListedItem> filesAndFolders, SortOption directorySortOption, SortDirection directorySortDirection)
{
var orderFunc = GetSortFunc(directorySortOption);
var naturalStringComparer = NaturalStringComparer.GetForProcessor();
// In ascending order, show folders first, then files.
// So, we use == StorageItemTypes.File to make the value for a folder equal to 0, and equal to 1 for the rest.
static bool folderThenFileAsync(ListedItem listedItem) => (listedItem.PrimaryItemAttribute == StorageItemTypes.File || listedItem.IsZipItem);
IOrderedEnumerable<ListedItem> ordered;
IUserSettingsService userSettingsService = Ioc.Default.GetService<IUserSettingsService>();
if (directorySortDirection == SortDirection.Ascending)
{
if (directorySortOption == SortOption.Name)
{
if (userSettingsService.PreferencesSettingsService.ListAndSortDirectoriesAlongsideFiles)
{
ordered = filesAndFolders.OrderBy(orderFunc, naturalStringComparer);
}
else
{
ordered = filesAndFolders.OrderBy(folderThenFileAsync).ThenBy(orderFunc, naturalStringComparer);
}
}
else if (directorySortOption == SortOption.FileTag)
{
if (userSettingsService.PreferencesSettingsService.ListAndSortDirectoriesAlongsideFiles)
{
ordered = filesAndFolders.OrderBy(x => string.IsNullOrEmpty(orderFunc(x) as string)).ThenBy(orderFunc);
}
else
{
ordered = filesAndFolders.OrderBy(folderThenFileAsync).ThenBy(x => string.IsNullOrEmpty(orderFunc(x) as string)).ThenBy(orderFunc);
}
}
else
{
if (userSettingsService.PreferencesSettingsService.ListAndSortDirectoriesAlongsideFiles)
{
ordered = filesAndFolders.OrderBy(orderFunc);
}
else
{
ordered = filesAndFolders.OrderBy(folderThenFileAsync).ThenBy(orderFunc);
}
}
}
else
{
if (directorySortOption == SortOption.Name)
{
if (userSettingsService.PreferencesSettingsService.ListAndSortDirectoriesAlongsideFiles)
{
ordered = filesAndFolders.OrderByDescending(orderFunc, naturalStringComparer);
}
else
{
ordered = filesAndFolders.OrderBy(folderThenFileAsync).ThenByDescending(orderFunc, naturalStringComparer);
}
}
else if (directorySortOption == SortOption.FileTag)
{
if (userSettingsService.PreferencesSettingsService.ListAndSortDirectoriesAlongsideFiles)
{
ordered = filesAndFolders.OrderBy(x => string.IsNullOrEmpty(orderFunc(x) as string)).ThenByDescending(orderFunc);
}
else
{
ordered = filesAndFolders.OrderBy(folderThenFileAsync).ThenBy(x => string.IsNullOrEmpty(orderFunc(x) as string)).ThenByDescending(orderFunc);
}
}
else
{
if (userSettingsService.PreferencesSettingsService.ListAndSortDirectoriesAlongsideFiles)
{
ordered = filesAndFolders.OrderByDescending(orderFunc);
}
else
{
ordered = filesAndFolders.OrderBy(folderThenFileAsync).ThenByDescending(orderFunc);
}
}
}
// Further order by name if applicable
if (directorySortOption != SortOption.Name)
{
if (directorySortDirection == SortDirection.Ascending)
{
ordered = ordered.ThenBy(orderByNameFunc, naturalStringComparer);
}
else
{
ordered = ordered.ThenByDescending(orderByNameFunc, naturalStringComparer);
}
}
return ordered;
}
19
Source : CloudProviderController.cs
with GNU General Public License v3.0
from files-community
with GNU General Public License v3.0
from files-community
public async Task<List<CloudProvider>> DetectInstalledCloudProvidersAsync()
{
var tasks = new List<Task<IList<CloudProvider>>>();
var results = new List<CloudProvider>();
foreach (var provider in CloudProviderDetectors)
{
tasks.Add(provider.DetectAsync());
}
await Task.WhenAll(tasks);
return tasks.SelectMany(o => o.Result).OrderBy(o => o.ID.ToString()).ThenBy(o => o.Name).Distinct().ToList();
}
19
Source : CloudDrivesDetector.cs
with GNU General Public License v3.0
from files-community
with GNU General Public License v3.0
from files-community
public static async Task<List<CloudProvider>> DetectCloudDrives()
{
var tasks = new List<Task<List<CloudProvider>>>()
{
Extensions.IgnoreExceptions(DetectOneDrive, Program.Logger),
Extensions.IgnoreExceptions(DetectSharepoint, Program.Logger),
Extensions.IgnoreExceptions(DetectGenericCloudDrive, Program.Logger)
};
await Task.WhenAll(tasks);
return tasks.Where(o => o.Result != null).SelectMany(o => o.Result).OrderBy(o => o.ID.ToString()).ThenBy(o => o.Name).Distinct().ToList();
}
19
Source : SnapPackageManager.cs
with MIT License
from fintermobilityas
with MIT License
from fintermobilityas
public void Sort()
{
ChecksumSummary = ChecksumSummary.OrderBy(x => x.SnapRelease.Version).ThenBy(x => x.SnapRelease.Filename).ToList();
DownloadSummary = DownloadSummary.OrderBy(x => x.SnapRelease.Version).ThenBy(x => x.SnapRelease.Filename).ToList();
RereplacedembleSummary = RereplacedembleSummary.OrderBy(x => x.SnapRelease.Version).ThenBy(x => x.SnapRelease.Filename).ToList();
}
19
Source : POTranslationRepository.cs
with BSD 3-Clause "New" or "Revised" License
from fintermobilityas
with BSD 3-Clause "New" or "Revised" License
from fintermobilityas
bool SaveTemplate(IDictionary<string, TemplateItem> items, string fileName)
{
var filePath = Path.Combine(GetAbsoluteLocaleDir(), !string.IsNullOrWhiteSpace(fileName) ? fileName : _localizationOptions.LocaleFilename) + ".pot";
if (File.Exists(filePath))
{
File.Delete(filePath);
}
if (!File.Exists(filePath))
{
var fileInfo = new FileInfo(filePath);
var dirInfo = new DirectoryInfo(Path.GetDirectoryName(filePath) ?? throw new InvalidOperationException());
if (!dirInfo.Exists)
{
dirInfo.Create();
}
fileInfo.Create().Close();
}
using var stream = new StreamWriter(filePath);
DebugHelpers.WriteLine("Writing file: {0}", filePath);
// Establish ordering of items in PO file.
var orderedItems = items.Values
// Non-orphan items before orphan items.
.OrderBy(x => x.References == null || !x.References.Any())
// Then order alphanumerically.
.ThenBy(x => x.MsgKey);
// This is required for poedit to read the files correctly if they contains
// for instance swedish characters.
stream.WriteLine("msgid \"\"");
stream.WriteLine("msgstr \"\"");
stream.WriteLine("\"Project-Id-Version: \\n\"");
stream.WriteLine("\"POT-Creation-Date: " + DateTime.Now.ToString("yyyy-MM-dd HH:mmzzz") + "\\n\"");
stream.WriteLine("\"MIME-Version: 1.0\\n\"");
stream.WriteLine("\"Content-Type: text/plain; charset=utf-8\\n\"");
stream.WriteLine("\"Content-Transfer-Encoding: 8bit\\n\"");
stream.WriteLine($"\"X-Generator: pot ({_replacedemblyVersion})\\n\"");
stream.WriteLine();
foreach (var item in orderedItems)
{
if (item.Comments != null)
{
foreach (var comment in item.Comments)
{
stream.WriteLine("#. " + comment);
}
}
foreach (var reference in item.References)
{
stream.WriteLine("#: " + reference.ToComment());
}
if (_localizationOptions.MessageContextEnabledFromComment
&& item.Comments != null
&& item.Comments.Any())
{
WriteString(stream, true, "msgctxt", item.Comments.First());
}
WriteString(stream, true, "msgid", Escape(item.MsgId));
WriteString(stream, true, "msgstr", string.Empty); // Enable loading of POT file into editor e.g. PoEdit.
stream.WriteLine(string.Empty);
}
return true;
}
19
Source : ABViewer.cs
with MIT License
from flashyiyi
with MIT License
from flashyiyi
public void LoadreplacedetBoundles()
{
UnloadreplacedetBoundles();
openedreplacedet = new HashSet<Object>();
enties = new List<ABEntiy>();
foreach (Object target in Selection.objects)
{
if (target is Defaultreplacedet)
{
string path = replacedetDatabase.GetreplacedetPath(target);
replacedetBundle ab = replacedetBundle.LoadFromFile(path);
if (ab == null)
break;
Object[] replacedets = ab.LoadAllreplacedets().Where(x => !(x is MonoScript) && x != null).OrderBy(x => x.GetType().Name).ThenBy(x => x.name).ToArray();
int count = replacedets.Length;
replacedetEntiy[] replacedetEntiys = new replacedetEntiy[count];
for (int i = 0;i < count;i++)
{
Object replacedet = replacedets[i];
replacedetEntiys[i] = new replacedetEntiy() { replacedet = replacedet, depends = EditorUtility.CollectDependencies(new Object[] { replacedet }).Where(x => !(x is MonoScript) && x != null).Except(new Object[] { replacedet }).OrderBy(x => x.GetType().Name).ThenBy(x => x.name).ToArray() };
}
enties.Add(new ABEntiy()
{
ab = ab,
abDepends = replacedetDatabase.GetreplacedetBundleDependencies(ab.name, false),
replacedets = replacedetEntiys,
depends = replacedetEntiys.SelectMany(x => x.depends).Distinct().OrderBy(x => x.GetType().Name).ThenBy(x => x.name).ToArray()
});
}
}
this.Repaint();
}
19
Source : InfoSidePage.cs
with MIT License
from floh22
with MIT License
from floh22
public List<PlayerTab> SetPlayersInOrder(List<PlayerTab> Players)
{
switch (Order)
{
case PlayerOrder.MaxToMin:
return Players.OrderByDescending(o => o.Values.MaxValue).ThenByDescending(o => o.Values.CurrentValue).ToList();
case PlayerOrder.MinToMax:
return Players.OrderBy(o => o.Values.MaxValue).ThenBy(o => o.Values.CurrentValue).ToList();
default:
break;
}
throw new Exception();
}
19
Source : QuickAccess.cs
with MIT License
from Flow-Launcher
with MIT License
from Flow-Launcher
internal static List<Result> AccessLinkListMatched(Query query, List<AccessLink> accessLinks)
{
if (string.IsNullOrEmpty(query.Search))
return new List<Result>();
string search = query.Search.ToLower();
var queriedAccessLinks =
accessLinks
.Where(x => x.Name.Contains(search, StringComparison.OrdinalIgnoreCase))
.OrderBy(x => x.Type)
.ThenBy(x => x.Name);
return queriedAccessLinks.Select(l => l.Type switch
{
ResultType.Folder => ResultManager.CreateFolderResult(l.Name, l.Path, l.Path, query, quickAccessResultScore),
ResultType.File => ResultManager.CreateFileResult(l.Path, query, quickAccessResultScore),
_ => throw new ArgumentOutOfRangeException()
}
19
Source : QuickAccess.cs
with MIT License
from Flow-Launcher
with MIT License
from Flow-Launcher
internal static List<Result> AccessLinkListAll(Query query, List<AccessLink> accessLinks)
=> accessLinks
.OrderBy(x => x.Type)
.ThenBy(x => x.Name)
.Select(l => l.Type switch
{
ResultType.Folder => ResultManager.CreateFolderResult(l.Name, l.Path, l.Path, query),
ResultType.File => ResultManager.CreateFileResult(l.Path, query, quickAccessResultScore),
_ => throw new ArgumentOutOfRangeException()
19
Source : QueryExpressionExpanderTests.cs
with MIT License
from fuse-open
with MIT License
from fuse-open
private void replacedertLookupCorrect<T, U>(IEnumerable<KeyValuePair<T, U>> actual, IList<Tuple<TextLocation, AstNode>> expected) where T : AstNode where U : AstNode {
var actualList = actual.OrderBy(x => x.Key.StartLocation).ThenBy(x => x.Key.GetType().ToString()).ToList();
replacedert.That(actualList.Select(x => x.Key.StartLocation).ToList(), Is.EqualTo(expected.Select(x => x.Item1).ToList()));
for (int i = 0; i < actualList.Count; i++) {
replacedert.That(actualList[i].Value, Is.Not.SameAs(actualList[i].Key));
replacedert.That(actualList[i].Value, Is.SameAs(expected[i].Item2));
}
}
19
Source : SOStringService.cs
with MIT License
from g3rv4
with MIT License
from g3rv4
private async Task RefreshCacheAsync(int? stringId = null, string familyKey = null)
{
string sql = $@"
Select Id, [Key], FamilyKey, OriginalString, Translation, NeedsPush, IsUrgent, IsIgnored, Variant, CreationDate
From Strings
Where IsNull(DeletionDate, @deletionDateLimit) >= @deletionDateLimit
{(stringId.HasValue ? "And Id = @stringId" : string.Empty)}
{(familyKey.HasValue() ? "And FamilyKey = @familyKey" : string.Empty)}
Order By IsUrgent Desc, OriginalString Asc;
Select ss.Id, ss.StringId, ss.Suggestion, ss.StateId State,
ss.CreatedById, u.DisplayName CreatedByName,
ss.LastStateUpdatedById, uu.DisplayName LastStateUpdatedByName,
ss.CreationDate
From StringSuggestions ss
Join Strings s On s.Id = ss.StringId And IsNull(s.DeletionDate, @deletionDateLimit) >= @deletionDateLimit
Join Users u On ss.CreatedById = u.Id
Left Join Users uu On uu.Id = ss.LastStateUpdatedById
Where ss.StateId In ({{=Created}}, {{=ApprovedByTrustedUser}})
{(stringId.HasValue ? "And s.Id = @stringId" : string.Empty)}
{(familyKey.HasValue() ? "And s.FamilyKey = @familyKey" : string.Empty)}";
using (MiniProfiler.Current.Step("Refreshing the strings cache"))
using (var db = _dbService.GetConnection())
using (var reader = await db.QueryMultipleAsync(sql, new
{
StringSuggestionState.Created,
StringSuggestionState.ApprovedByTrustedUser,
stringId,
familyKey,
deletionDateLimit = DateTime.UtcNow.AddDays(-5)
}))
{
var strings = (await reader.ReadAsync<SOString>()).AsList();
var suggestions = (await reader.ReadAsync<SOStringSuggestion>()).AsList();
Dictionary<int, SOString> stringsById;
using (MiniProfiler.Current.Step("Attaching the suggestions to the strings"))
{
stringsById = strings.ToDictionary(s => s.Id);
foreach (var g in suggestions.GroupBy(g => g.StringId))
{
if (stringsById.TryGetValue(g.Key, out var str))
{
str.Suggestions = g.ToArray();
}
}
}
if (stringId.HasValue)
{
StringsById[stringId.Value] = stringsById[stringId.Value];
Strings = StringsById.Values.OrderByDescending(s => s.IsUrgent).ThenBy(s => s.OriginalString).ToImmutableArray();
}
else if (familyKey.HasValue())
{
foreach (var str in strings)
{
StringsById[str.Id] = str;
}
Strings = StringsById.Values.OrderByDescending(s => s.IsUrgent).ThenBy(s => s.OriginalString).ToImmutableArray();
}
else
{
StringsById = stringsById;
Strings = strings.ToImmutableArray();
}
}
}
19
Source : ConsulDiscoverySource.cs
with Apache License 2.0
from gigya
with Apache License 2.0
from gigya
private IEnumerable<EndPoint> OrderedEndpoints(IEnumerable<EndPoint> endpoints)
{
return endpoints.OrderBy(x => x.HostName).ThenBy(x => x.Port);
}
19
Source : AggregatingHealthStatus.cs
with Apache License 2.0
from gigya
with Apache License 2.0
from gigya
private HealthCheckResult HealthCheck()
{
DisposableHealthCheck[] checks;
lock (_locker)
{
checks = _checks.ToArray(); // get the current state of the health-checks list
}
// don't call the health check functions inside a lock. It may run for a long time,
// and in the worse case it may cause a dead-lock, if the function is locking something else that we depend on
var results = checks
.Select(c => new { c.Name, Result = c.CheckFunc() })
.OrderBy(c => c.Result.Health)
.ThenBy(c => c.Name)
.ToArray();
bool allHealthy = results.All(r => r.Result.Health != Health.Unhealthy);
string message = string.Join(Environment.NewLine,
results
.Where(r => r.Result.SuppressMessage==false)
.Select(r =>
(r.Result.Health == Health.Healthy ? "[OK] " :
r.Result.Health==Health.Unhealthy ? "[Unhealthy] "
: "")
+ $"{r.Name}: {r.Result.Message}"));
var formattableMessage = message.Replace("{", "{{").Replace("}", "}}"); // HealthCheckResult is formatting the message string using "string.Format"
return allHealthy ? HealthCheckResult.Healthy(formattableMessage) : HealthCheckResult.Unhealthy(formattableMessage);
}
19
Source : FunctionsStartupAttribute.cs
with Apache License 2.0
from GoogleCloudPlatform
with Apache License 2.0
from GoogleCloudPlatform
public static IEnumerable<Type> GetStartupTypes(replacedembly replacedembly, Type? target)
{
var fromreplacedembly = replacedembly.GetCustomAttributes<FunctionsStartupAttribute>();
var fromType = target?.GetCustomAttributes<FunctionsStartupAttribute>(inherit: true) ?? Enumerable.Empty<FunctionsStartupAttribute>();
return fromreplacedembly.Concat(fromType)
.OrderBy(attr => attr.Order)
.ThenBy(attr => attr.StartupType.FullName)
.Select(attr => attr.StartupType)
.ToList();
}
19
Source : ReferenceImageCatalog.cs
with Apache License 2.0
from googlevr
with Apache License 2.0
from googlevr
public void RequestLoadImages(int iMin, int iMax) {
iMin = Mathf.Max(0, iMin);
iMax = Mathf.Min(m_Images.Count, iMax);
var newRequests = m_RequestedLoads
.Concat(Enumerable.Range(iMin, iMax - iMin))
.Distinct()
.OrderBy(i => m_Images[i].Running ? 0 : 1)
.ThenBy(i => (iMin <= i && i < iMax) ? 0 : 1);
m_RequestedLoads = new Stack<int>(newRequests.Reverse());
Resources.UnloadUnusedreplacedets();
}
19
Source : CatalogPagingFilteringModel.cs
with GNU General Public License v3.0
from grandnode
with GNU General Public License v3.0
from grandnode
public virtual async Task PrepareSpecsFilters(IList<string> alreadyFilteredSpecOptionIds,
IList<string> filterableSpecificationAttributeOptionIds,
ISpecificationAttributeService specificationAttributeService,
string url, string langId)
{
Enabled = false;
var allFilters = new List<SpecificationAttributeOptionFilter>();
foreach (var sao in filterableSpecificationAttributeOptionIds.Union(alreadyFilteredSpecOptionIds))
{
var sa = await specificationAttributeService.GetSpecificationAttributeByOptionId(sao);
if (sa != null)
{
allFilters.Add(new SpecificationAttributeOptionFilter {
SpecificationAttributeId = sa.Id,
SpecificationAttributeName = sa.GetTranslation(x => x.Name, langId),
SpecificationAttributeSeName = sa.SeName,
SpecificationAttributeDisplayOrder = sa.DisplayOrder,
SpecificationAttributeOptionId = sao,
SpecificationAttributeOptionName = sa.SpecificationAttributeOptions.FirstOrDefault(x => x.Id == sao).GetTranslation(x => x.Name, langId),
SpecificationAttributeOptionSeName = sa.SpecificationAttributeOptions.FirstOrDefault(x => x.Id == sao).SeName,
SpecificationAttributeOptionDisplayOrder = sa.SpecificationAttributeOptions.FirstOrDefault(x => x.Id == sao).DisplayOrder,
SpecificationAttributeOptionColorRgb = sa.SpecificationAttributeOptions.FirstOrDefault(x => x.Id == sao).ColorSquaresRgb,
});
}
}
if (!allFilters.Any())
return;
//sort loaded options
allFilters = allFilters.OrderBy(saof => saof.SpecificationAttributeDisplayOrder)
.ThenBy(saof => saof.SpecificationAttributeName)
.ThenBy(saof => saof.SpecificationAttributeOptionDisplayOrder)
.ThenBy(saof => saof.SpecificationAttributeOptionName).ToList();
//prepare the model properties
Enabled = true;
var removeFilterUrl = url;
foreach (var item in allFilters.GroupBy(x => x.SpecificationAttributeSeName))
{
removeFilterUrl = CommonExtensions.ModifyQueryString(removeFilterUrl, item.Key, null);
}
RemoveFilterUrl = ExcludeQueryStringParams(removeFilterUrl);
//get already filtered specification options
var alreadyFilteredOptions = allFilters.Where(x => alreadyFilteredSpecOptionIds.Contains(x.SpecificationAttributeOptionId));
AlreadyFilteredItems = alreadyFilteredOptions.Select(x =>
{
var alreadyFiltered = alreadyFilteredOptions.Where(y => y.SpecificationAttributeId == x.SpecificationAttributeId).Select(z => z.SpecificationAttributeOptionSeName)
.Except(new List<string> { x.SpecificationAttributeOptionSeName }).ToList();
var filterUrl = CommonExtensions.ModifyQueryString(url, x.SpecificationAttributeSeName, GenerateFilteredSpecQueryParam(alreadyFiltered));
return new SpecificationFilterItem {
SpecificationAttributeName = x.SpecificationAttributeName,
SpecificationAttributeSeName = x.SpecificationAttributeSeName,
SpecificationAttributeOptionName = x.SpecificationAttributeOptionName,
SpecificationAttributeOptionSeName = x.SpecificationAttributeOptionSeName,
SpecificationAttributeOptionColorRgb = x.SpecificationAttributeOptionColorRgb,
FilterUrl = ExcludeQueryStringParams(filterUrl)
};
}).ToList();
//get not filtered specification options
NotFilteredItems = allFilters.Except(alreadyFilteredOptions).Select(x =>
{
//filter URL
var alreadyFiltered = alreadyFilteredOptions.Where(y => y.SpecificationAttributeId == x.SpecificationAttributeId).Select(x => x.SpecificationAttributeOptionSeName)
.Concat(new List<string> { x.SpecificationAttributeOptionSeName });
var filterUrl = CommonExtensions.ModifyQueryString(url, x.SpecificationAttributeSeName, GenerateFilteredSpecQueryParam(alreadyFiltered.ToList()));
return new SpecificationFilterItem() {
SpecificationAttributeName = x.SpecificationAttributeName,
SpecificationAttributeSeName = x.SpecificationAttributeSeName,
SpecificationAttributeOptionName = x.SpecificationAttributeOptionName,
SpecificationAttributeOptionSeName = x.SpecificationAttributeOptionSeName,
SpecificationAttributeOptionColorRgb = x.SpecificationAttributeOptionColorRgb,
FilterUrl = ExcludeQueryStringParams(filterUrl)
};
}).ToList();
}
19
Source : Substrate.cs
with GNU General Public License v3.0
from Gravemind2401
with GNU General Public License v3.0
from Gravemind2401
internal static Plugin GetDefaultHandler(OpenFileArgs args)
{
if (App.Settings.DefaultHandlers.ContainsKey(args.FileTypeKey))
{
var handlerKey = App.Settings.DefaultHandlers[args.FileTypeKey];
if (plugins.ContainsKey(handlerKey)) //in case the plugin is no longer installed
return plugins[handlerKey];
}
var handler = AllPlugins
.Where(p => p.CanOpenFile(args))
.OrderByDescending(p => p.FilePriority ?? int.MaxValue)
.ThenBy(p => p.Name)
.FirstOrDefault();
if (handler == null)
return handler;
if (App.Settings.DefaultHandlers.ContainsKey(args.FileTypeKey))
App.Settings.DefaultHandlers.Remove(args.FileTypeKey);
App.Settings.DefaultHandlers.Add(args.FileTypeKey, handler.Key);
return handler;
}
19
Source : ArchiveEditViewModel.cs
with GNU General Public License v3.0
from Guerra24
with GNU General Public License v3.0
from Guerra24
private void ReloadTagsList(string tags)
{
TagsList.Clear();
foreach (var t in tags.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).OrderByDescending(t => t.Contains(":")).ThenBy(t => t.Trim()))
TagsList.Add(ColorTag(new EditableTag { Tag = t.Trim(), Command = TagCommand }));
TagsList.Add(new AddTag { Command = TagCommand });
Tags = BuildTags();
}
19
Source : SortTests.cs
with GNU Lesser General Public License v2.1
from gustavnavar
with GNU Lesser General Public License v2.1
from gustavnavar
private bool ValidateSorting<T, TNext>(TestGrid grid, Func<TestModel, T> orderExpression,
string columnName,
GridSortDirection direction,
Func<TestModel, TNext> thenByExpression,
GridSortDirection? thenByDirection,
IComparer<T> comparer,
IComparer<TNext> nextComparer)
{
grid.AddQueryParameter(((QueryStringSortSettings)grid.Settings.SortSettings)
.ColumnQueryParameterName, columnName);
grid.AddQueryParameter(((QueryStringSortSettings)grid.Settings.SortSettings)
.DirectionQueryParameterName, direction.ToString("d"));
grid.UpdateGrid().Wait();
IEnumerable<TestModel> resultCollection = grid.GereplacedemsToDisplay();
IOrderedEnumerable<TestModel> etalonCollection;
switch (direction)
{
case GridSortDirection.Ascending:
if (comparer == null)
etalonCollection = _repo.GetAll().OrderBy(orderExpression);
else
etalonCollection = _repo.GetAll().OrderBy(orderExpression, comparer);
break;
case GridSortDirection.Descending:
if (comparer == null)
etalonCollection = _repo.GetAll().OrderByDescending(orderExpression);
else
etalonCollection = _repo.GetAll().OrderByDescending(orderExpression, comparer);
break;
default:
throw new ArgumentOutOfRangeException("direction");
}
if (thenByExpression != null)
{
switch (thenByDirection)
{
case GridSortDirection.Ascending:
if (nextComparer == null)
etalonCollection = etalonCollection.ThenBy(thenByExpression);
else
etalonCollection = etalonCollection.ThenBy(thenByExpression, nextComparer);
break;
case GridSortDirection.Descending:
if (nextComparer == null)
etalonCollection = etalonCollection.ThenByDescending(thenByExpression);
else
etalonCollection = etalonCollection.ThenByDescending(thenByExpression, nextComparer);
break;
default:
throw new ArgumentOutOfRangeException("thenByDirection");
}
}
if (!ValidateCollectionsTheSame(resultCollection, etalonCollection))
{
return false;
}
return true;
}
19
Source : SortTests.cs
with GNU Lesser General Public License v2.1
from gustavnavar
with GNU Lesser General Public License v2.1
from gustavnavar
private bool ValidateSorting<T, TNext>(TestGrid grid, Func<TestModel, T> orderExpression,
string columnName,
GridSortDirection direction,
Func<TestModel, TNext> thenByExpression,
GridSortDirection? thenByDirection,
IComparer<T> comparer,
IComparer<TNext> nextComparer)
{
var settingsMock = new Mock<IGridSettingsProvider>();
settingsMock.Setup(s => s.SortSettings.ColumnName).Returns(columnName);
settingsMock.Setup(s => s.SortSettings.Direction).Returns(direction);
settingsMock.Setup(s => s.FilterSettings).Returns(new QueryStringFilterSettings(_query));
settingsMock.Setup(s => s.SearchSettings).Returns(new QueryStringSearchSettings(_query));
grid.Settings = settingsMock.Object;
IEnumerable<TestModel> resultCollection = _grid.GereplacedemsToDisplay();
IOrderedEnumerable<TestModel> etalonCollection;
switch (direction)
{
case GridSortDirection.Ascending:
if(comparer == null)
etalonCollection = _repo.GetAll().OrderBy(orderExpression);
else
etalonCollection = _repo.GetAll().OrderBy(orderExpression, comparer);
break;
case GridSortDirection.Descending:
if (comparer == null)
etalonCollection = _repo.GetAll().OrderByDescending(orderExpression);
else
etalonCollection = _repo.GetAll().OrderByDescending(orderExpression, comparer);
break;
default:
throw new ArgumentOutOfRangeException("direction");
}
if (thenByExpression != null)
{
switch (thenByDirection)
{
case GridSortDirection.Ascending:
if (nextComparer == null)
etalonCollection = etalonCollection.ThenBy(thenByExpression);
else
etalonCollection = etalonCollection.ThenBy(thenByExpression, nextComparer);
break;
case GridSortDirection.Descending:
if (nextComparer == null)
etalonCollection = etalonCollection.ThenByDescending(thenByExpression);
else
etalonCollection = etalonCollection.ThenByDescending(thenByExpression, nextComparer);
break;
default:
throw new ArgumentOutOfRangeException("thenByDirection");
}
}
if (!ValidateCollectionsTheSame(resultCollection, etalonCollection))
{
return false;
}
return true;
}
19
Source : GameDataGathering.cs
with MIT License
from gw2scratch
with MIT License
from gw2scratch
private Task<(IEnumerable<SpeciesData>, IEnumerable<SkillData>)> ParseLogs(IReadOnlyCollection<LogData> logs,
CancellationToken cancellationToken, IProgress<(int done, int totalLogs, int failed)> progress = null)
{
return Task.Run(() =>
{
var species = new Dictionary<int, Dictionary<SpeciesData, List<LogData>>>();
var skills = new Dictionary<uint, Dictionary<SkillData, List<LogData>>>();
int done = 0;
int failed = 0;
foreach (var log in logs)
{
cancellationToken.ThrowIfCancellationRequested();
Log processedLog;
try
{
var parsedLog = Parser.ParseLog(log.FileName);
processedLog = Processor.ProcessLog(parsedLog);
}
catch
{
failed++;
continue;
}
foreach (var agent in processedLog.Agents.OfType<NPC>())
{
int id = agent.SpeciesId;
string name = agent.Name;
// Ignore missing data. If the species id, in most cases all other data is meaningless.
if (id == 0) continue;
var speciesData = new SpeciesData(id, name);
if (!species.ContainsKey(id))
{
species[id] = new Dictionary<SpeciesData, List<LogData>>();
}
if (!species[id].ContainsKey(speciesData))
{
species[id][speciesData] = new List<LogData>();
}
species[id][speciesData].Add(log);
}
foreach (var skill in processedLog.Skills)
{
uint id = skill.Id;
string name = skill.Name;
// Ignore missing data. If the species id, in most cases all other data is meaningless.
if (id == 0) continue;
var skillData = new SkillData(id, name);
if (!skills.ContainsKey(id))
{
skills[id] = new Dictionary<SkillData, List<LogData>>();
}
if (!skills[id].ContainsKey(skillData))
{
skills[id][skillData] = new List<LogData>();
}
skills[id][skillData].Add(log);
}
done++;
progress?.Report((done, logs.Count, failed));
}
var speciesEnumerable = (IEnumerable<SpeciesData>) species.Values.SelectMany(x => x).Select(x =>
{
var key = x.Key;
key.Logs.AddRange(x.Value);
return key;
}).OrderBy(x => x.SpeciesId)
.ThenBy(x => x.Name);
var skillEnumerable = (IEnumerable<SkillData>) skills.Values.SelectMany(x => x).Select(x =>
{
var key = x.Key;
key.Logs.AddRange(x.Value);
return key;
}).OrderBy(x => x.SkillId)
.ThenBy(x => x.Name);
return (speciesEnumerable, skillEnumerable);
}, cancellationToken);
}
See More Examples