public static void Sort(ref List <TroopRosterElement> sortedTroops, ref List <TroopRosterElement> heroTroops, SorterConfiguration configuration) { sortedTroops = configuration.CurrentThenByMode == SortMode.NONE || configuration.CurrentThenByMode == configuration.CurrentSortByMode ? sortedTroops.SortBy(configuration.CurrentSortByMode, configuration).ToList() : sortedTroops.SortBy(configuration.CurrentSortByMode, configuration) .ThenSortBy(configuration.CurrentThenByMode, configuration) .ToList(); heroTroops = configuration.CurrentThenByMode == SortMode.NONE || configuration.CurrentThenByMode == configuration.CurrentSortByMode ? heroTroops.SortBy(configuration.CurrentSortByMode, configuration).ToList() : heroTroops.SortBy(configuration.CurrentSortByMode, configuration) .ThenSortBy(configuration.CurrentThenByMode, configuration) .ToList(); if (!configuration.UpgradableOnTop) { return; } // TODO: Re-visit this to use PartyCharacterVM to allow better sorting and upgrade detection List <TroopRosterElement> upgradableTroops = sortedTroops.Where(x => x.NumberReadyToUpgrade > 0).ToList(); upgradableTroops = upgradableTroops.OrderByDescending(x => x.Character.UpgradeRequiresItemFromCategory == null).ToList(); sortedTroops = sortedTroops.Where(x => x.NumberReadyToUpgrade <= 0).ToList(); sortedTroops.InsertRange(0, upgradableTroops); }
static void Main() { var elements = new List<int>() { 40, 50, 60, 5, 10, 20, 30, }; var ordered = elements.SortBy(x => x); Console.WriteLine(string.Join(", ", ordered)); var students = new List<Student>() { new Student("Gosho", 20, 4.5), new Student("Pesho", 17, 2), new Student("Tanio", 23, 6.00), new Student("Ivan", 21, 5.5) }; var goodStudents = students .Filter(st => st.AverageGrade > 5) .SortBy(st => st.Age) .Project(st => st.Name); Console.WriteLine(string.Join("\n", goodStudents)); }
public static void GiveAllShortHashes() { ShortHashGiver.takenHashesPerDeftype.Clear(); List <Def> list = new List <Def>(); foreach (Type current in GenDefDatabase.AllDefTypesWithDatabases()) { Type type = typeof(DefDatabase <>).MakeGenericType(new Type[] { current }); PropertyInfo property = type.GetProperty("AllDefs"); MethodInfo getMethod = property.GetGetMethod(); IEnumerable enumerable = (IEnumerable)getMethod.Invoke(null, null); list.Clear(); foreach (Def item in enumerable) { list.Add(item); } list.SortBy((Def d) => d.defName); for (int i = 0; i < list.Count; i++) { ShortHashGiver.GiveShortHash(list[i], current); } } }
private static void Main() { var elements = new List <int> { 40, 50, 60, 5, 10, 20, 30 }; var ordered = elements.SortBy(x => x); Console.WriteLine(string.Join(", ", ordered)); var students = new List <Student> { new Student("Gosho", 20, 4.5), new Student("Pesho", 17, 2), new Student("Tanio", 23, 6.00), new Student("Ivan", 21, 5.5) }; var goodStudents = students.Filter(st => st.AverageGrade > 5).SortBy(st => st.Age).Project(st => st.Name); var ivan = students.FirstOrDef(st => st.Name == "Ivan"); // var goodStudents = students.Where(st => st.AverageGrade > 5).OrederBy(st => st.Age).Select(st => st.Name); //tova e LINQ varianta na gornata zaivka Console.WriteLine(string.Join("\n", goodStudents)); }
public static void DiscoverRandomDeity() { List <CosmicEntity> discoverable = new List <CosmicEntity>(); if (deities == null) { return; } foreach (CosmicEntity deity in deities) { if (!deity.isDiscovered) { discoverable.Add(deity); } } if (discoverable.Count == 0) { Log.Message("Discovered all deities"); return; } // select random and discover int index = Math.Abs(Rand.Int) % discoverable.Count; //Log.Message(Rand.Int.ToString() + " % " + discoverable.Count + " = " + index); Messages.Message("Discovered " + discoverable[index].def.label, null, MessageTypeDefOf.PositiveEvent); discoverable[index].Discover(); //.Add(new CosmicEntity(){ def = available_defs[index] }); // sort list deities.SortBy(d => d.def.index); }
//private static void AddEveryMedicineToRelevantThings(Pawn pawn, Thing billGiver, List<Thing> relevantThings, Predicate<Thing> baseValidator, Map map) public static void Postfix(Pawn pawn, Thing billGiver, List <Thing> relevantThings, Map map) { if (HackityGetBill.bill == null) { Verse.Log.Warning($"Smart Medicine Inventory Surgery not going to work for {pawn}; mod conflict in AddEveryMedicineToRelevantThings or TryFindBestBillIngredients?"); return; } Predicate <Thing> baseValidator = (Thing t) => HackityGetBill.bill.IsFixedOrAllowedIngredient(t) && HackityGetBill.bill.recipe.ingredients.Any((IngredientCount ingNeed) => ingNeed.filter.Allows(t)); Log.Message($"AddEveryMedicineToRelevantThings ({pawn}, {billGiver}, {HackityGetBill.bill})"); MedicalCareCategory medicalCareCategory = (MedicalCareCategory)AccessTools.Method(typeof(WorkGiver_DoBill), "GetMedicalCareCategory").Invoke(null, new object[] { billGiver }); Log.Message($"inventory: ({pawn.inventory.GetDirectlyHeldThings().ToStringSafeEnumerable()})"); foreach (Thing t in pawn.inventory.GetDirectlyHeldThings()) { if (medicalCareCategory.AllowsMedicine(t.def) && baseValidator(t)) { Log.Message($"{pawn} considering {t} for surgery on {billGiver}"); relevantThings.Add(t); } } //Tiny addition to use minimal medicine for Anesthetize bill. TODO: Make this a def extension so any recipe could use it, though no one will so why really int statAdjust = (Settings.Get().minimalMedicineForNonUrgent&& HackityGetBill.bill.recipe == Anesthetize ? 1 : -1); relevantThings.SortBy( (Thing x) => statAdjust * x.GetStatValue(StatDefOf.MedicalPotency), //Check if item is in inventory or spawned in map: inventory "distance" is 0 (Thing x) => x.Spawned ? x.Position.DistanceToSquared(billGiver.Position) : 0); HackityGetBill.bill = null; }
public InterestList() : base() { List <InterestDef> tmpList = new List <InterestDef>(DefDatabase <InterestDef> .AllDefsListForReading); if (tmpList.Count == 0) { throw new System.ArgumentException("DInterests: Must have at least 1 PassionDef, failed to find any. Loading at least 3 is highly recommended."); } // For compatability, try to make our first indices match the original enum InterestDef[] defaults = { InterestDefOf.DNoPassion, InterestDefOf.DMinorPassion, InterestDefOf.DMajorPassion }; // 0, 1, 2 foreach (InterestDef def in defaults) { var find = tmpList.FindAll(x => x == def); if (!find.NullOrEmpty()) { AddRange(find); tmpList.Remove(find[0]); } } tmpList.SortBy(x => x.priority); AddRange(tmpList); this.process(); }
internal void DisplayRecords(List <StudentEntity> results) { try { //Filtering data before display it if (_filters != null && _filters.Count > 0) { results = results.Where(_filters).ToList(); } //Sorting data before display it if (_sortByColumns != null && _sortByColumns.Count > 0) { results = results.SortBy(_sortByColumns).ToList(); } foreach (var entity in results) { Console.WriteLine(entity.ToString()); } } catch (Exception ex) { string errorMessage = $"Error displaying records from the list of students."; throw new StudentException(errorMessage, ex); } }
//private static void AddEveryMedicineToRelevantThings(Pawn pawn, Thing billGiver, List<Thing> relevantThings, Predicate<Thing> baseValidator, Map map) public static void Postfix(Pawn pawn, Thing billGiver, List <Thing> relevantThings, Map map) { if (HackityGetBill.bill == null) { Verse.Log.Warning($"Smart Medicine Inventory Surgery not going to work for {pawn}; mod conflict in AddEveryMedicineToRelevantThings or TryFindBestBillIngredients?"); return; } Predicate <Thing> baseValidator = (Thing t) => HackityGetBill.bill.IsFixedOrAllowedIngredient(t) && HackityGetBill.bill.recipe.ingredients.Any((IngredientCount ingNeed) => ingNeed.filter.Allows(t)); Log.Message($"AddEveryMedicineToRelevantThings ({pawn}, {billGiver}, {HackityGetBill.bill})"); MedicalCareCategory medicalCareCategory = (MedicalCareCategory)AccessTools.Method(typeof(WorkGiver_DoBill), "GetMedicalCareCategory").Invoke(null, new object[] { billGiver }); bool added = false; Log.Message($"inventory: ({pawn.inventory.GetDirectlyHeldThings().ToStringSafeEnumerable()})"); foreach (Thing t in pawn.inventory.GetDirectlyHeldThings()) { if (medicalCareCategory.AllowsMedicine(t.def) && baseValidator(t)) { Log.Message($"{pawn} considering {t} for surgery on {billGiver}"); added = true; relevantThings.Add(t); } } if (added) { relevantThings.SortBy((Thing x) => - x.GetStatValue(StatDefOf.MedicalPotency, true), (Thing x) => x.Spawned ? x.Position.DistanceToSquared(billGiver.Position) : 0); } HackityGetBill.bill = null; }
public static bool CaravanOrRichestColonyHasAnyOf(ThingDef thingdef, Caravan caravan, out Thing thing) { if (CaravanInventoryUtility.TryGetThingOfDef(caravan, thingdef, out thing, out Pawn owner)) { return(true); } List <Map> maps = Find.Maps.FindAll(x => x.IsPlayerHome); if (maps.NullOrEmpty()) { return(false); } maps.SortBy(x => x.PlayerWealthForStoryteller); Map richestMap = maps.First(); if (thingdef.IsBuildingArtificial) { return(FindBuildingOrMinifiedVersionThereOf(thingdef, richestMap, out thing)); } var thingsOfDef = richestMap.listerThings.ThingsOfDef(thingdef); thing = thingsOfDef.FirstOrDefault(); return(thingsOfDef.Any()); }
private static List <IItem> ClientSelectItemsToConsume( IProtoItemWithFuel protoItemWithFuel, double amountNeeded, int maxItemsToConsume) { var fuelProtoItems = protoItemWithFuel.ItemFuelConfig.FuelProtoItemsList; var itemsToConsume = new List <IItem>(); var character = Client.Characters.CurrentPlayerCharacter; var containerInventory = character.SharedGetPlayerContainerInventory(); var containerHotbar = character.SharedGetPlayerContainerHotbar(); var allItems = containerInventory.Items.Concat(containerHotbar.Items); itemsToConsume.AddRange(allItems.Where(i => fuelProtoItems.Contains(i.ProtoItem))); itemsToConsume.SortBy(i => ((IProtoItemFuel)i.ProtoItem).FuelAmount); for (var i = 0; i < itemsToConsume.Count; i++) { var item = itemsToConsume[i]; amountNeeded -= item.Count * ((IProtoItemFuel)item.ProtoItem).FuelAmount; maxItemsToConsume -= item.Count; if (amountNeeded <= 0 || maxItemsToConsume <= 0) { // that's enough - don't consume all the remaining items itemsToConsume.RemoveRange(startingIndex: i + 1); } } return(itemsToConsume); }
public override void ProcessInput(Event ev) { base.ProcessInput(ev); List <FloatMenuOption> list = new List <FloatMenuOption>(); if (settables == null) { settables = new List <IPlantToGrowSettable>(); } if (!settables.Contains(settable)) { settables.Add(settable); } tmpAvailablePlants.Clear(); foreach (ThingDef item in PlantUtility.ValidPlantTypesForGrowers(settables)) { if (IsPlantAvailable(item, settable.Map)) { tmpAvailablePlants.Add(item); } } tmpAvailablePlants.SortBy((ThingDef x) => 0f - GetPlantListPriority(x), (ThingDef x) => x.label); for (int i = 0; i < tmpAvailablePlants.Count; i++) { ThingDef plantDef = tmpAvailablePlants[i]; string text = plantDef.LabelCap; if (plantDef.plant.sowMinSkill > 0) { text = text + (string)(" (" + "MinSkill".Translate() + ": ") + plantDef.plant.sowMinSkill + ")"; } list.Add(new FloatMenuOption(text, delegate { string s = tutorTag + "-" + plantDef.defName; if (TutorSystem.AllowAction(s)) { bool flag = true; for (int j = 0; j < settables.Count; j++) { settables[j].SetPlantDefToGrow(plantDef); if (flag && plantDef.plant.interferesWithRoof) { foreach (IntVec3 cell in settables[j].Cells) { if (cell.Roofed(settables[j].Map)) { Messages.Message("MessagePlantIncompatibleWithRoof".Translate(Find.ActiveLanguageWorker.Pluralize(plantDef.LabelCap)), MessageTypeDefOf.CautionInput, historical: false); flag = false; break; } } } } PlayerKnowledgeDatabase.KnowledgeDemonstrated(ConceptDefOf.SetGrowingZonePlant, KnowledgeAmount.Total); WarnAsAppropriate(plantDef); TutorSystem.Notify_Event(s); } }, plantDef, MenuOptionPriority.Default, null, null, 29f, (Rect rect) => Widgets.InfoCardButton(rect.x + 5f, rect.y + (rect.height - 24f) / 2f, plantDef))); } Find.WindowStack.Add(new FloatMenu(list)); }
private void TryFillQuota() { BodyParts = new List <BodyPartRecord>(); if (Surgery?.Worker == null || Surgery.addsHediff == null) { return; } Pawn_HealthTracker pHealth = Patient.health; foreach (BodyPartRecord part in Surgery.Worker.GetPartsToApplyOn(Patient, Surgery)) { if (pHealth.surgeryBills.Bills.Any(b => b is Bill_Medical bill && bill.Part == part && bill.recipe == Surgery)) { continue; } if (pHealth.hediffSet.hediffs.Where(h => h.def.defName == Surgery.addsHediff.defName).Any(h => h.Part == part)) { continue; } BodyParts.Add(part); } BodyParts.SortBy(part => HealHelper.GetAverageHealthOfPart(Patient, part)); BodyParts = BodyParts.Take(Quantity).ToList(); }
public List <Thing> GetForCell(IntVec3 cell, float radius, List <MeditationFocusOffsetPerBuilding> defs, Thing forThing = null) { CellRequest key = new CellRequest(cell, radius, defs, forThing); if (!requestCache.TryGetValue(key, out var value)) { value = new List <Thing>(); foreach (Thing t2 in GenRadial.RadialDistinctThingsAround(cell, map, radius, useCenter: false)) { if (defs.Any((MeditationFocusOffsetPerBuilding d) => d.building == t2.def) && t2.GetRoom() == cell.GetRoom(map) && t2 != forThing) { value.Add(t2); } } value.SortBy(delegate(Thing t) { float num = t.Position.DistanceTo(cell); MeditationFocusOffsetPerBuilding meditationFocusOffsetPerBuilding = defs.FirstOrDefault((MeditationFocusOffsetPerBuilding d) => d.building == t.def); if (meditationFocusOffsetPerBuilding != null) { num -= meditationFocusOffsetPerBuilding.offset * 100000f; } return(num); }); requestCache[key] = value; } return(value); }
public static void ResolveCollisions() { var seenHashes = new HashSet <ushort>(); var defsToRehash = new List <Def>(); foreach (Type current in GenDefDatabase.AllDefTypesWithDatabases()) { var type = typeof(DefDatabase <>).MakeGenericType(current); var property = type.GetProperty("AllDefs"); var getMethod = property.GetGetMethod(); var allDefsInDatabase = (IEnumerable)getMethod.Invoke(null, null); defsToRehash.Clear(); foreach (Def def in allDefsInDatabase) { if (seenHashes.Contains(def.shortHash)) { defsToRehash.Add(def); } else { seenHashes.Add(def.shortHash); } } defsToRehash.SortBy(d => d.defName); for (int i = 0; i < defsToRehash.Count; i++) { var def = defsToRehash[i]; def.shortHash = 0; InjectedDefHasher.GiveShortHasToDef(def); Log.Message(def.defName + " " + def.shortHash); } seenHashes.Clear(); } }
public static List <Pawn> SortedAnimalList(IEnumerable <Thing> pawnEnumerable) { List <Pawn> pawnList = pawnEnumerable.Cast <Pawn>().ToList(); pawnList.SortBy(p => !p.HasBondRelation(), p => p.LabelShort); return(pawnList); }
protected override Job TryGiveJob(Pawn pawn) { tmpChemicalNeeds.Clear(); List <Need> allNeeds = pawn.needs.AllNeeds; for (int i = 0; i < allNeeds.Count; i++) { if (ShouldSatisfy(allNeeds[i])) { tmpChemicalNeeds.Add((Need_Chemical)allNeeds[i]); } } if (!tmpChemicalNeeds.Any()) { return(null); } tmpChemicalNeeds.SortBy((Need_Chemical x) => x.CurLevel); for (int j = 0; j < tmpChemicalNeeds.Count; j++) { Thing thing = FindDrugFor(pawn, tmpChemicalNeeds[j]); if (thing != null) { tmpChemicalNeeds.Clear(); return(DrugAIUtility.IngestAndTakeToInventoryJob(thing, pawn, 1)); } } tmpChemicalNeeds.Clear(); return(null); }
public static string PawnKindsToCommaList(IEnumerable <PawnKindDef> pawnKinds, bool useAnd = false) { tmpPawnKinds.Clear(); tmpPawnKinds.AddRange(pawnKinds); if (tmpPawnKinds.Count >= 2) { tmpPawnKinds.SortBy((PawnKindDef x) => !x.RaceProps.Humanlike, (PawnKindDef x) => GenLabel.BestKindLabel(x, Gender.None, plural: true)); } tmpAddedPawnKinds.Clear(); tmpPawnKindsStr.Clear(); for (int i = 0; i < tmpPawnKinds.Count; i++) { if (!tmpAddedPawnKinds.Contains(tmpPawnKinds[i])) { tmpAddedPawnKinds.Add(tmpPawnKinds[i]); int num = 0; for (int j = 0; j < tmpPawnKinds.Count; j++) { if (tmpPawnKinds[j] == tmpPawnKinds[i]) { num++; } } if (num == 1) { tmpPawnKindsStr.Add("1 " + GenLabel.BestKindLabel(tmpPawnKinds[i], Gender.None)); } else { tmpPawnKindsStr.Add(num + " " + GenLabel.BestKindLabel(tmpPawnKinds[i], Gender.None, plural: true, num)); } } } return(tmpPawnKindsStr.ToCommaList(useAnd)); }
public static string PawnKindsToCommaList(IEnumerable <Pawn> pawns, bool useAnd = false) { tmpPawns.Clear(); tmpPawns.AddRange(pawns); if (tmpPawns.Count >= 2) { tmpPawns.SortBy((Pawn x) => !x.RaceProps.Humanlike, (Pawn x) => x.GetKindLabelPlural()); } tmpAddedPawnKinds.Clear(); tmpPawnKindsStr.Clear(); for (int i = 0; i < tmpPawns.Count; i++) { if (!tmpAddedPawnKinds.Contains(tmpPawns[i].kindDef)) { tmpAddedPawnKinds.Add(tmpPawns[i].kindDef); int num = 0; for (int j = 0; j < tmpPawns.Count; j++) { if (tmpPawns[j].kindDef == tmpPawns[i].kindDef) { num++; } } if (num == 1) { tmpPawnKindsStr.Add("1 " + tmpPawns[i].KindLabel); } else { tmpPawnKindsStr.Add(num + " " + tmpPawns[i].GetKindLabelPlural(num)); } } } return(tmpPawnKindsStr.ToCommaList(useAnd)); }
public static void AppendInspectStringsFromQuestParts(Action <string, Quest> func, ISelectable target, out int count) { count = 0; List <Quest> questsListForReading = Find.QuestManager.QuestsListForReading; for (int i = 0; i < questsListForReading.Count; i++) { if (questsListForReading[i].State != QuestState.Ongoing) { continue; } _ = questsListForReading[i].State; tmpQuestParts.Clear(); tmpQuestParts.AddRange(questsListForReading[i].PartsListForReading); tmpQuestParts.SortBy((QuestPart x) => (x is QuestPartActivable) ? ((QuestPartActivable)x).EnableTick : 0); for (int j = 0; j < tmpQuestParts.Count; j++) { QuestPartActivable questPartActivable = tmpQuestParts[j] as QuestPartActivable; if (questPartActivable != null && questPartActivable.State == QuestPartState.Enabled) { string str = questPartActivable.ExtraInspectString(target); if (!str.NullOrEmpty()) { func(str.Formatted(target.Named("TARGET")), questsListForReading[i]); count++; } } } tmpQuestParts.Clear(); } }
public static void AddEveryMedicineToRelevantThings2( Pawn pawn, Thing billGiver, List <Thing> relevantThings, Predicate <Thing> baseValidator, Map map) { MedicalCareCategory medicalCareCategory = GetMedicalCareCategory(billGiver); WorkGiver_DoBill_RegionProcessor.thingList = map.listerThings.ThingsInGroup(ThingRequestGroup.Medicine); //WorkGiver_DoBill.tmpMedicine.Clear(); List <Thing> tmpMedicine = new List <Thing>(); for (int index = 0; index < WorkGiver_DoBill_RegionProcessor.thingList.Count; ++index) { Thing thing = WorkGiver_DoBill_RegionProcessor.thingList[index]; if (medicalCareCategory.AllowsMedicine(thing.def) && baseValidator(thing) && pawn.CanReach(thing, PathEndMode.OnCell, Danger.Deadly, false, TraverseMode.ByPawn)) { tmpMedicine.Add(thing); } } tmpMedicine.SortBy(x => - x.GetStatValue(StatDefOf.MedicalPotency, true), x => x.Position.DistanceToSquared(billGiver.Position)); relevantThings.AddRange(tmpMedicine); //WorkGiver_DoBill.tmpMedicine.Clear(); }
static void Main() { var elements = new List <int>() { 40, 50, 60, 5, 10, 20, 30, }; var ordered = elements.SortBy(x => x); Console.WriteLine(string.Join(", ", ordered)); var students = new List <Student>() { new Student("Gosho", 20, 4.5), new Student("Pesho", 17, 2), new Student("Tanio", 23, 6.00), new Student("Ivan", 21, 5.5) }; var goodStudents = students .Filter(st => st.AverageGrade > 5) .SortBy(st => st.Age) .Project(st => st.Name); Console.WriteLine(string.Join("\n", goodStudents)); }
public static List <Thing> SortedByValue(List <Thing> list) { if (Settings.Get().tradeRequestWorstFirst) { list.SortBy(t => t.MarketValue); } return(list); }
public override void ContextMenuAction(Designator designator, Map map) { var des = (Designator_SelectSimilar)designator; var reverse = des as Designator_SelectSimilarReverse; if (reverse != null) { des = reverse.GetNonReverseVersion(); } if (Find.Selector.NumSelected == 0) { Messages.Message("Designator_context_similar_fail".Translate(), MessageTypeDefOf.RejectInput); return; } des.ReindexSelectionConstraints(); // find things to select List <Thing> thingsToSelect = new List <Thing>(); foreach (var thing in map.listerThings.AllThings) { if (des.CanDesignateThing(thing).Accepted) { thingsToSelect.Add(thing); } } // sort by distance to camera var cameraCenter = Current.CameraDriver.MapPosition; thingsToSelect.SortBy(t => t.Position.DistanceTo(cameraCenter)); // do selection var hitCount = 0; var limitWasHit = false; foreach (var thing in thingsToSelect) { if (!des.SelectionLimitAllowsAdditionalThing()) { limitWasHit = true; break; } if (des.TrySelectThing(thing)) { hitCount++; } } if (limitWasHit) { Messages.Message("Designator_context_similar_part".Translate(hitCount, thingsToSelect.Count), MessageTypeDefOf.TaskCompletion); } else { Messages.Message("Designator_context_similar_succ".Translate(hitCount), MessageTypeDefOf.TaskCompletion); } }
/// <summary> /// Constructs a PatchNotesDisplayWindow class and saves the current Text.Font, Text.Anchor and GUI.color /// </summary> public PatchNotesDisplayWindow() { patchNotesScrollViewRect = PatchNotesScrollArea.LeftPartPixels(PatchNotesScrollArea.width - 17f); basePatchNoteRect = patchNotesScrollViewRect.TopPartPixels(45f); CalculateScrollViewSize(); patchNoteDefs.SortBy((def) => def.ReleaseDate, (def) => def.ToOldEmpireVersion); patchNoteDefs.Reverse(); }
public override void PostLoad() { base.PostLoad(); if (parts != null) { List <StatPart> partsCopy = parts.ToList(); parts.SortBy((StatPart x) => 0f - x.priority, (StatPart x) => partsCopy.IndexOf(x)); } }
public void SortByWithKeyTest_Key_IsNull_Throw_ArgumentNullException() { List <int> source = new List <int>() { 1, 2, 3, 4 }; Func <int, int> key = null; Assert.Throws <ArgumentNullException>(() => source.SortBy(key)); }
public void SortByTest_IfComparer_IsNull_Throw_ArgumentNullException() { List <int> source = new List <int>() { 1, 2, 3, 4 }; Comparison <int> comparer = null; Assert.Throws <ArgumentNullException>(() => source.SortBy(comparer)); }
public void SortByDateProperty() { List <Sortable> list = GetList(); list.SortBy("Date"); Assert.IsTrue(list[0].Name == "Zander"); Assert.IsTrue(list[1].Name == "Ted"); Assert.IsTrue(list[2].Name == "Bill"); }
public void SortByStringPropertyDesc() { List <Sortable> list = GetList(); list.SortBy("Name", SortDirection.Descending); Assert.IsTrue(list[0].Name == "Zander"); Assert.IsTrue(list[1].Name == "Ted"); Assert.IsTrue(list[2].Name == "Bill"); }
public void SortByStringAndIntProperty() { List <Sortable> list = GetList(); list.SortBy("Name", "Age"); Assert.IsTrue(list[0].Name == "Bill"); Assert.IsTrue(list[1].Name == "Ted"); Assert.IsTrue(list[2].Name == "Zander"); }
private static void Main() { var elements = new List<int> { 40, 50, 60, 5, 10, 20, 30 }; var ordered = elements.SortBy(x => x); Console.WriteLine(string.Join(", ", ordered)); var students = new List<Student> { new Student("Gosho", 20, 4.5), new Student("Pesho", 17, 2), new Student("Tanio", 23, 6.00), new Student("Ivan", 21, 5.5) }; var goodStudents = students.Filter(st => st.AverageGrade > 5).SortBy(st => st.Age).Project(st => st.Name); var ivan = students.FirstOrDef(st => st.Name == "Ivan"); // var goodStudents = students.Where(st => st.AverageGrade > 5).OrederBy(st => st.Age).Select(st => st.Name); //tova e LINQ varianta na gornata zaivka Console.WriteLine(string.Join("\n", goodStudents)); }
private ICollection<ProductListItem> SearchProducts(ProductFilterModel filter) { var products = new List<ProductListItem>(); bool isSelectedAnyPlatform = filter.Platforms != null && filter.Platforms.Any(p => p.Selected); bool isSelectedAnyGenre = filter.Genres != null && filter.Genres.Any(p => p.Selected); bool isSelectedAnyPegi = filter.PegiRatings != null && filter.PegiRatings.Any(p => p.Selected); IEnumerable<SelectListItem> selectedPlatforms = null; IEnumerable<SelectListItem> selectedPegis = null; IEnumerable<SelectListItem> selectedGenres = null; if (isSelectedAnyGenre) { selectedGenres = filter.Genres.Where(p => p.Selected == true); } if (isSelectedAnyPegi) { selectedPegis = filter.PegiRatings.Where(p => p.Selected == true); } if (isSelectedAnyPlatform) { selectedPlatforms = filter.Platforms.Where(p => p.Selected == true); } foreach (var prod in ProductManager.Products.ToList()) { if (!prod.IsDeleted && prod.Name.Contains(filter.SearchKeyword != null ? filter.SearchKeyword : string.Empty)) { if (isSelectedAnyGenre && !selectedGenres.Any(g => g.Value == prod.GenreId.ToString())) { continue; } if (isSelectedAnyPlatform && !selectedPlatforms.Any(p => p.Value == prod.PlatformId.ToString())) { continue; } if (isSelectedAnyPegi && !selectedPegis.Any(p => p.Value == prod.PegiRatingId.ToString())) { continue; } products.Add(prod.ToListItem()); } } return products.SortBy(filter.ProductSortType).ToList(); }