Is there An Efficient way of combining two collections? - c#

I have classes as follows:
public class Root
{
public int Id {get;set;}
public string PlayerName{get;set;}
}
public class Scores:Root
{
public int GameT{get;set;}
public int GameZ{get;set;}
}
public class Experience:Root
{
public int ExT{get;set;}
public int ExZ{get;set;}
}
public class Total:Root
{
public int TotalT{get;set;}
public int TotalZ{get;set}
}
TotalT and TotalZ are got from adding GameT, ExT and GameZ, ExZ respectively. I have an observable collection of scores and Experience from which I want to create another collection of Total, here is what I have done so far:
public ObservableCollection<Total> GetTotal(ObservableCollection<Scores> scores,ObservableCollection<Experience> experiences)
{
var tc= new ObservableCollection<Total>();
foreach(var scr in scores)
{
foreach(var exp in experiences)
{
if(scr.Id==exp.Id)
{
var tt= new Total{
Id=scr.Id,
Name=scr.PlayerName,
TotalT=scr.GameT+exp.Ext,
TotalZ=scr.GameZ+exp.Exz
};
tc.Add(tt);
}
}
}
return tc;
}
It works but it is too slow, especially when the records begin to hit hundreds. Is there a better way?

It looks like you just want a LINQ inner join:
var query = from score in scores
join exp in experiences on score.Id equals exp.Id
select new Total {
Id = score.Id,
Name = score.PlayerName,
TotalT = score.GameT + exp.Ext,
TotalZ = score.GameZ + exp.Exz
};
return new ObservableCollection<Total>(query);
That will be more efficient by iterating over all the experiences to start with, collecting them by ID, then iterating over the scores, matching each score with the collection of associated experiences. Basically it turns an O(M * N) operation into an O(M + N) operation.

Maybe I'm mistaken, but wouldn't be a good idea to observe the observable collections and collect totals in real time and accumulate results somewhere instead of trying to address the issue all at once?
It's all about implementing observer/observable pattern. Since you can subscribe to collection changes, you can do stuff whenever the collection change. You can also implement INotifyPropertyChanged on Experience.ExT and Experience.ExZ and subscribe to changes of every property from all objects.
This way, you don't need to work on hundred of objects but you just show what's has been accumulated during some period of time.

Related

C# Generic List<T> update items

I'm using a List<T> and I need to update the objects properties that the list has.
What would be the most efficient/faster way to do this? I know that scanning through the index of a List<T> would be slower as this list grows and that the List<T> is not the most efficient collection to do updates.
That sad, would be better to:
Remove the match object then add a new one?
Scan through the list indexes until you find the matching object and then update the object's properties?
If I have a collection, let's IEnumerable and I want to update that IEnumerable into the List, what would be best approach.
Stub code sample:
public class Product
{
public int ProductId { get; set; }
public string ProductName { get; set; }
public string Category { get; set; }
}
public class ProductRepository
{
List<Product> product = Product.GetProduct();
public void UpdateProducts(IEnumerable<Product> updatedProduct)
{
}
public void UpdateProduct(Product updatedProduct)
{
}
}
You could consider using Dictionary instead of List if you want fast lookups. In your case it would be the product Id (which I am assuming is unique). Dictionary MSDN
For example:
public class ProductRepository
{
Dictionary<int, Product> products = Product.GetProduct();
public void UpdateProducts(IEnumerable<Product> updatedProducts)
{
foreach(var productToUpdate in updatedProducts)
{
UpdateProduct(productToUpdate);
}
///update code here...
}
public void UpdateProduct(Product productToUpdate)
{
// get the product with ID 1234
if(products.ContainsKey(productToUpdate.ProductId))
{
var product = products[productToUpdate.ProductId];
///update code here...
product.ProductName = productToUpdate.ProductName;
}
else
{
//add code or throw exception if you want here.
products.Add(productToUpdate.ProductId, productToUpdate);
}
}
}
Your use case is updating a List<T>, which can contains millions of records, and updated records can be a sub-list or just a single record
Following is the Schema:
public class Product
{
public int ProductId { get; set; }
public string ProductName { get; set; }
public string Category { get; set; }
}
Does Product contains a primary key, which means every Product object can be uniquely identified and there are no duplicates and every update target a single unique record?
If Yes, then it is best to arrange the List<T> in the form of Dictionary<int,T>, which would mean for an IEnumerable<T> every update would be an O(1) time complexity and that would mean all the updates could be done depending on the size of the IEnumerable<T>, which i don't expect to be very big and though there would be extra memory allocation of different data structure required, but would be a very fast solution.#JamieLupton has already provided a solution on similar lines
In case Product is repeated, there's no primary key, then above solution is not valid, then ideal way to scan through the List<T> is Binary Search, whose time complexity is O(logN)
Now since size of IEnumerable<T> is comparatively small say M, so the overall time complexity would be O(M*logN), where M is much smaller than N and can be neglected.
List<T> support Binary Search API, which provides the element index, which can then be used to update the object at relevant index, check example here
Best Option as per me for such a high number of records would be parallel processing along with binary search
Now since, thread safety is an issue, what I normally do is divide a List<T> into List<T>[], since then each unit can be assigned to a separate thread, a simple way is use MoreLinq batch Api, where you can fetch the number of system processors as using Environment.ProcessorCount and then create IEnumerable<IEnumerable<T>> as follows:
var enumerableList = List<T>.Batch(Environment.ProcessorCount).ToList();
Another way is following custom code:
public static class MyExtensions
{
// data - List<T>
// dataCount - Calculate once and pass to avoid accessing the property everytime
// Size of Partition, which can be function of number of processors
public static List<T>[] SplitList<T>(this List<T> data, int dataCount, int partitionSize)
{
int remainderData;
var fullPartition = Math.DivRem(dataCount, partitionSize, out remainderData);
var listArray = new List<T>[fullPartition];
var beginIndex = 0;
for (var partitionCounter = 0; partitionCounter < fullPartition; partitionCounter++)
{
if (partitionCounter == fullPartition - 1)
listArray[partitionCounter] = data.GetRange(beginIndex, partitionSize + remainderData);
else
listArray[partitionCounter] = data.GetRange(beginIndex, partitionSize);
beginIndex += partitionSize;
}
return listArray;
}
}
Now you can create Task[], where each Task is assigned for every element List<T>, on the List<T>[] generated above, then Binary search for each sub partition. Though its repetitive but would be using the power of Parallel processing and Binary search. Each Task can be started and then we can wait using Task.WaitAll(taskArray) to wait for Task processing to finish
Over and above that, if you want to create a Dictionary<int,T>[] and thus use parallel processing then this would be fastest.
Final integration of List<T>[] to List<T> can be done using Linq Aggregation or SelectMany as follows:
List<T>[] splitListArray = Fetch splitListArray;
// Process splitListArray
var finalList = splitListArray.SelectMany(obj => obj).ToList()
Another option would be to use Parallel.ForEach along with a thread safe data structure like ConcurrentBag<T> or may be ConcurrentDictionary<int,T> in case you are replacing complete object, but if its property update then a simple List<T> would work. Parallel.ForEach internally use range partitioner similar to what I have suggested above
Solutions mentioned above ideally depends on your use case, you shall be able to use combination to achieve the best possible result. Let me know, in case you need specific example
What exactly is efficiency?
Unless there are literally thousands of items doing a foreach, or for or any other type of looping operation will most likely only show differences in the milleseconds. Really? Hence you have wasted more time (in costs of a programmer at $XX per hour than an end user costs) trying to find that best.
So if you have literally thousands of records I would recommend that efficiency be found by parallel processing the list with the Parallel.Foreach method which can process more records to save time with the overhead of threading.
IMHO if the record count is greater than 100 it implies that there is a database being used. If a database is involved, write an update sproc and call it a day; I would be hard pressed to write a one-off program to do a specific update which could be done in an easier fashion in said database.

How should I remove elements from a generic list based on the list s object's inclusion of elementfrom another list in C# using predicate logic?

I am trying to learn C# by making a simple program that shows the user sushi rolls given their desired ingredients. i.e. a user wants a roll with crab, and the program will spit out a list of sushi rolls that contain crab.
I've created a Roll class
public class Roll
{
private string name;
private List<string> ingredients = new List<string>();
}
With some getters and setters and other various methods.
In the GUI, I have some checkboxes which each call an update() method from the Control class, which will then need to check a list of rolls against a list of ingredients given by the GUI checkboxes. What I have is this
class Controller
{
static List<Roll> Rolls = new List<Roll>();
static RollList RL = new RollList();
static List<String> ingredients = new List<String>();
static Roll roll = new Roll();
}
public void update
{
foreach(Roll roll in Rolls)
{
foreach (String ingredient in ingredients)
if (!roll.checkForIngredient(ingredient))
Rolls.Remove(roll);
}
}
But a System.InvalidOperationException is thrown saying that because the collection was modified, the operation can't execute. OK, that's fair, but then what's the best way to do this? Here on Stack Overflow there's a post about removing elements from a generic list while iterating over it.
This was good and pointed me in the right direction, but unfortunately, my predicate condition simply doesn't match the top answer's.
It would have to iterate over the ingredients list, and I'm not even sure that's possible...
list.RemoveAll(roll => !roll.containsIngredient(each string ingredient in ingredients) );
shudder
I've tried the for loop, but I can't seem to get the enumeration to work either, and I wonder if it's even necessary to enumerate the class for just this method.
So I come here to try and find an elegant, professional solution to my problem. Keep in mind that I'm new to C# and I'm not all too familiar with predicate logic or enumeration on classes.
To use RemoveAll you can rewrite your condition to this:
list.RemoveAll(roll => !ingredients.All(roll.checkForIngredient));
This exploits the fact that when the compiler sees this, it will effectively rewrite it to this:
list.RemoveAll(roll => !ingredients.All(i => roll.checkForIngredient(i)));
Which is what you want. If not all the ingredients are present, remove the roll.
Now, having said that, since you say you're a beginner, perhaps you feel more comfortable keeping your loop, if you could just make it work (ie. stop crashing due to modifying the loop). To do that, just make a copy of the collection and then loop through the copy, you can do this by just modifying the foreach statement to this:
foreach(Roll roll in Rolls.ToList())
This will create a list based copy of the Rolls collection, and then loop on that. The list will not be modified, even if Rolls is, it is a separate copy containing all the elements of Rolls when it was created.
As requested in the comments, I'll try to explain how this line of code works:
list.RemoveAll(roll => !ingredients.All(roll.checkForIngredient));
The RemoveAll method, which you can see the documentation for here takes a predicate, a Predicate<T>, which is basically a delegate, a reference to a method.
This can be a lambda, syntax that creates an anonymous method, using the => operator. An anonymous method is basically a method declared where you want to use it, without a name, hence the anonymous part. Let's rewrite the code to use an anonymous method instead of a lambda:
list.RemoveAll(delegate(Roll roll)
{
return !ingredients.All(roll.checkForIngredient);
});
This is the exact same compiled code as for the lambda version above, just using the bit more verbose syntax of an anonymous method.
So, how does the code inside the method work.
The All method is an extension method, found on the Enumerable class: Enumerable.All.
It will basically loop through all the elements of the collection it is extending, in this case the ingredients collection of a single roll, and call the predicate function. If for any of the elements the predicate returns false, the result of calling All will also be false. If all the calls return true, the result will also be true. Note that if the collection (ingredients) is empty, the result will also be true.
So let's try to rewrite our lambda code, which again looked like this:
list.RemoveAll(roll => !ingredients.All(roll.checkForIngredient));
Into a more verbose method, not using the All extension method:
list.RemoveAll(delegate(Roll roll)
{
bool all = true;
foreach (var ingredient in ingredients)
if (!roll.checkForIngredient(ingredient))
{
all = false;
break;
}
return !all;
});
This now starts to look like your original piece of code, except that we're using the RemoveAll method, which needs a predicate that returns whether to remove the item or not. Since if all is false, we need to remove the roll, we use the not operator ! to reverse that value.
Since you are both new to C# but also asked for an elegant solution, I will give you an example of how to solve this using a more object-oriented approach.
First of all, any "thing" of significance should be modeled as a class, even if it has just one property. This makes it easier to extend the behavior later on. You already defined a class for Roll. I would also add a class for Ingredient:
public class Ingredient
{
private string _name;
public string Name
{
get { return _name; }
}
public Ingredient(string name)
{
_name = name;
}
}
Note the Name property which only has a getter, and the constructor which accepts a string name. This might look like unnecessary complexity at first but will make your code more straightforward to consume further down the road.
Next, we'll modify your Roll class according to this guideline and give it some helper methods that make it easier for us to check if a roll contains a certain (list of) ingredients:
public class Roll
{
private string _name;
private List<Ingredient> _ingredients = new List<Ingredient>();
public string Name
{
// By only exposing the property through a getter, you are preventing the name
// from being changed after the roll has been created
get { return _name; }
}
public List<Ingredient> Ingredients
{
// Similarly here, you are forcing the consumer to use the AddIngredient method
// where you can do any necessary checks before actually adding the ingredient
get { return _ingredients; }
}
public Roll(string name)
{
_name = name;
}
public bool AddIngredient(Ingredient ingredient)
{
// Returning a boolean value to indicate whether the ingredient was already present,
// gives the consumer of this class a way to present feedback to the end user
bool alreadyHasIngredient = _ingredients.Any(i => i.Name == ingredient.Name);
if (!alreadyHasIngredient)
{
_ingredients.Add(ingredient);
return true;
}
return false;
}
public bool ContainsIngredients(IEnumerable<Ingredient> ingredients)
{
// We use a method group to check for all of the supplied ingredients
// whether or not they exist
return ingredients.All(ContainsIngredient);
// Could be rewritten as: ingredients.All(i => ContainsIngredient(i));
}
public bool ContainsIngredient(Ingredient ingredient)
{
// We simply check if an ingredient is present by comparing their names
return _ingredients.Any(i => i.Name == ingredient.Name);
}
}
Pay attention to the ContainsIngredient and ContainsIngredients methods here. Now you can do stuff like if (roll.ContainsIngredient(ingredient)), which will make your code more expressive and more readable. You'll see this in action in the next class that I'm going to add, RollCollection.
You are modeling collections of food to pick from, presumably in the context of a restaurant menu or some similar domain. You might as well go ahead and model just that: a RollCollection. This will allow you to encapsulate some meaningful logic inside of the collection.
Again, this sort of thing tends to require some boilerplate code and may look overly complex at first, but it will make your classes easier to consume. So let's add a RollCollection:
public class RollCollection : IEnumerable<Roll>
{
private List<Roll> _rolls = new List<Roll>();
public RollCollection()
{
// We need to provide a default constructor if we want to be able
// to instantiate an empty RollCollection and then add rolls later on
}
public RollCollection(IEnumerable<Roll> rolls)
{
// By providing a constructor overload which accepts an IEnumerable<Roll>,
// we have the opportunity to create a new RollCollection based on a filtered existing collection of rolls
_rolls = rolls.ToList();
}
public RollCollection WhichContainIngredients(IEnumerable<Ingredient> ingredients)
{
IEnumerable<Roll> filteredRolls = _rolls
.Where(r => r.ContainsIngredients(ingredients));
return new RollCollection(filteredRolls);
}
public bool AddRoll(Roll roll)
{
// Similar to AddIngredient
bool alreadyContainsRoll = _rolls.Any(r => r.Name == roll.Name);
if (!alreadyContainsRoll)
{
_rolls.Add(roll);
return true;
}
return false;
}
#region IEnumerable implementation
public IEnumerator<Roll> GetEnumerator()
{
foreach (Roll roll in _rolls)
{
yield return roll;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
}
WhichContainIngredients is the thing we were really looking for, as it allows you to do something like this:
// I have omitted the (proper) instantiation of Rolls and ChosenIngredients for brevity here
public RollCollection Rolls { get; set; }
public List<Ingredient> ChosenIngredients { get; set; }
public void Update()
{
Rolls = Rolls.WhichContainIngredients(ChosenIngredients);
}
This is simple and clean, just the sort of thing you want to be doing in your presentation layer. The logic to accomplish your requirement is now nicely encapsulated in the RollCollection class.
EDIT: a more complete (but still simplified) example of how your Controller class might end up looking like:
public class Controller
{
private RollCollection _availableRolls = new RollCollection();
private List<Ingredient> _availableIngredients = new List<Ingredient>();
public RollCollection AvailableRolls
{
get { return _availableRolls; }
}
public List<Ingredient> AvailableIngredients
{
get { return _availableIngredients; }
}
public RollCollection RollsFilteredByIngredients
{
get { return AvailableRolls.WhichContainIngredients(ChosenIngredients); }
}
public List<Ingredient> ChosenIngredients { get; set; }
public Controller()
{
ChosenIngredients = new List<Ingredient>();
InitializeTestData();
}
private void InitializeTestData()
{
Ingredient ingredient1 = new Ingredient("Ingredient1");
Ingredient ingredient2 = new Ingredient("Ingredient2");
Ingredient ingredient3 = new Ingredient("Ingredient3");
_availableIngredients.Add(ingredient1);
_availableIngredients.Add(ingredient2);
_availableIngredients.Add(ingredient3);
Roll roll1 = new Roll("Roll1");
roll1.AddIngredient(ingredient1);
roll1.AddIngredient(ingredient2);
Roll roll2 = new Roll("Roll2");
roll2.AddIngredient(ingredient3);
_availableRolls.AddRoll(roll1);
_availableRolls.AddRoll(roll2);
}
}
I am trying to learn C# by making a simple program that shows the user
sushi rolls given their desired ingredients. i.e. a user wants a roll
with crab, and the program will spit out a list of sushi rolls that
contain crab.
Here's my solution to the given problem:
public class Roll
{
public string Name { get; set; }
private List<string> ingredients = new List<string>();
public IList<string> Ingredients { get { return ingredients; } }
public bool Contains(string ingredient)
{
return Ingredients.Any(i => i.Equals(ingredient));
}
}
You can use the LINQ extension method .Where to filter your collection of Rolls
public class Program
{
static void Main()
{
var allRolls = new List<Roll>
{
new Roll
{
Name = "Roll 1",
Ingredients = { "IngredientA", "Crab", "IngredientC" }
},
new Roll
{
Name = "Roll 2",
Ingredients = { "IngredientB", "IngredientC" }
},
new Roll
{
Name = "Roll 3",
Ingredients = { "Crab", "IngredientA" }
}
};
var rollsWithCrab = allRolls.Where(roll => roll.Contains("Crab"));
foreach (Roll roll in rollsWithCrab)
{
Console.WriteLine(roll.Name);
}
}
}
From what I see you're trying to remove all rolls that don't contain crab from your list of rolls. A better approach is to filter out those rolls that don't contain crab (using .Where), you can then use .ToList() if you need to manipulate the whole list directly rather than iterating through the collection (fetching one item at a time).
You should read up on Delegates, Iterators, Extension Methods and LINQ to better understand what's going on under the covers.

remove duplicates items from a collection except its first occurance

I have a Collection of type string that can contain any number of elements.
Now i need to find out all those elements that are duplicating and find out only the first occurance of duplicating elements and delete rest.
For ex
public class CollectionCategoryTitle
{
public long CollectionTitleId { get; set; }
public bool CollectionTitleIdSpecified { get; set; }
public string SortOrder { get; set; }
public TitlePerformance performanceField { get; set; }
public string NewOrder { get; set; }
}
List<CollectionCategoryTitle> reorderTitles =
(List<CollectionCategoryTitle>)json_serializer
.Deserialize<List<CollectionCategoryTitle>>(rTitles);
Now i need to process this collection in such a way tat it removes duplicates but it must keep the 1st occurance.
EDIT:
I have updated the code and i need to compare on "NewOrder " property
Thanks
For your specific case:
var withoutDuplicates = reorderTitles.GroupBy(z => z.NewOrder).Select(z => z.First()).ToList();
For the more general case, Distinct() is generally preferable. For example:
List<int> a = new List<int>();
a.Add(4);
a.Add(1);
a.Add(2);
a.Add(2);
a.Add(4);
a = a.Distinct().ToList();
will return 4, 1, 2. Note that Distinct doesn't guarantee the order of the returned data (the current implementation does seem to return them based on the order of the original data - but that is undocumented and thus shouldn't be relied upon).
Use the Enumerable.Distinct<T>() extension method to do this.
EDIT: mjwills correctly points out that guaranteed ordering is important in the question, so the other two suggestions are not spec-guaranteed to work. Leaving just the one that gives this guarantee.
private static IEnumerable<CollectionCategoryTitle> DistinctNewOrder(IEnumerable<CollectionCategoryTitle> src)
{
HashSet<string> seen = new HashSet<string>();
//for one last time, change for different string comparisons, such as
//new HashSet<string>(StringComparer.CurrentCultureIgnoreCase)
foreach(var item in src)
if(seen.Add(item.NewOrder))
yield return item;
}
/*...*/
var distinctTitles = reorderTitles.DistinctNewOrder().ToList();
Finally, only use .ToList() after the call to DistinctNewOrder() if you actually need it to be a list. If you're going to process the results once and then do no further work, you're better off not creating a list which wastes time and memory.

How to use method(s) to add multiple, changing values

I'm working on a personal project for a friend and have hit a bit of a roadblock. I can continue as I am and write some really redundant code, but I feel there must be a more efficient way of doing this.
What I'm trying to do is write a method that will add three values and display the results to the text box under "Skill Modifier" header (see screenshot). I need to get the method, or a series of methods, to do that for each skill. It needs to get the Skill Modifier value for Balance, Climb, Escape Artist, etc...
The method would be something like "CalculateSM"
What I have currently:
private void btnUpdate_Click(object sender, EventArgs e)
{
//AM + R + MM =SM
//AM = Ability Modifier
//R = Rank
//MM = Misc Modifier
//SM = Skill Modifier
decimal balanceMod = balanceAM.Value + balanceR.Value + balanceMM.Value;
balanceSM.Text = balanceMod.ToString();
decimal climbMod = climbAM.Value + climbR.Value + climbMM.Value;
climbSM.Text = climbMod.ToString();
//etc...
}
Essentially the biggest issue, for me, is figuring out how to contrive a method that can deal with so many different field names and add them in the same way. I'd like to avoid copy and pasting the same two lines of code fifty times over for each and every skill.
Any ideas would be much appreciated! Thank you.
using fields like this is not very object-oriented. you're probably going to want to introduce a Skills class that implements the method to calculate the final skill score and then use some Skills objects for different skills.
public class Skill
{
int ability, rank, misc;
public Skill(int ability, int rank, int misc)
{
this.ability = ability;
this.rank = rank;
this.misc = misc;
}
public int Score { get { return ability + rank + misc; }
}
Skill balance = new Skill(10, 1, 1);
textBalance.Text = balance.Score.ToString();
Skill programming = new Skill(10, 100, 0);
textProgramming.Text = programming.Score.ToString();
also, think of a clever way to tie the skills to your user controls. you're not going to like ending up with 50 text boxes that are all alike except for a bit of a name. a first step could be to wire them all up to the same event handler, for example.
Normally, the approach would be to create a class which represents one row of your skills screen. You could then keep a list of these in some way (say, List<Skill>). You could then quite easily loop through all of them:
foreach (Skill skill in character.Skills)
{
// do something with the skill object
}
The trick would be to dynamically generate the user interface. It's not actually very hard to do this (although a bit too much code to go into here), by far the easiest approach would be to use something like a DataGridView. It should be fairly easy to google for examples, or just ask if you want specific info.
Looks like you have an object collection which you could databind to something in the UI (like a data grid or something)
Modify the values calculate things, what you could do in some example code:
class Skill
{
public string Name { get; set; }
public string KeyAbility { get; set; }
public int SkillModifier { get; set; }
public int AbilityModifier { get; set; }
public int Ranks { get; set; }
public int MiscModifier { get; set; }
void Calculate()
{
//Formula goes here
//Set the SkillModifier
}
}
Skill balance = new Skill() { Name = "Balance" }
Basically you can make a collection of skills, update through what ever UI object you bind to etc. Using fields the way you are atm is very redundant and using OO you can achieve the same with alot less work.
Basically in You'd create a collection of the Skill class, with Balance and all other skills you mentioned. Databind this collection to something in the UI, allow for updating, call different methods. You could even implement some inheritance for different type of skills. With a Skill base class.
What type are balanceAM, balanceR etc?
Can they not derive from a base type or interface that you can use to pass to a helper method?
private string GetText(IModel modelAM, IModel modelR, IModel modelMM)
{
return modelAM.Value + modelR.Value + modelMM.Value;
}
balanceSM.Text = this.GetText(balanceAM, balanceR, balanceMM);
Ok, the fact that you only have private fields for each individual control is your core problem. You're probably better off creating a list of structs to store them:
struct PickYourOwnNameHere
{
Control SM;
Control AM;
Control R;
Control MM;
}
List<PickYourOwnNameHere> skills = new List<PickYourOwnNameHere>();
Obviously, populate that list on initialization, and then you can just do:
skills.ForEach(skill =>
skill.SM.Text = (skill.AM.Value + skill.R.Value + skill.MM.Value).ToString()
);
I'm doing that syntax from memory, but hopefully you get the idea.

Converting nested foreach loops to LINQ

I've written the following code to set the properties on various classes. It works, but one of my new year's rsolutions is to make as much use of LINQ as possible and obviously this code doesn't. Is there a way to rewrite it in a "pure LINQ" format, preferably without using the foreach loops? (Even better if it can be done in a single LINQ statement - substatements are fine.)
I tried playing around with join but that didn't get me anywhere, hence I'm asking for an answer to this question - preferably without an explanation, as I'd prefer to "decompile" the solution to figure out how it works. (As you can probably guess I'm currently a lot better at reading LINQ than writing it, but I intend to change that...)
public void PopulateBlueprints(IEnumerable<Blueprint> blueprints)
{
XElement items = GetItems();
// item id => name mappings
var itemsDictionary = (
from item in items
select new
{
Id = Convert.ToUInt32(item.Attribute("id").Value),
Name = item.Attribute("name").Value,
}).Distinct().ToDictionary(pair => pair.Id, pair => pair.Name);
foreach (var blueprint in blueprints)
{
foreach (var material in blueprint.Input.Keys)
{
if (itemsDictionary.ContainsKey(material.Id))
{
material.Name = itemsDictionary[material.Id];
}
else
{
Console.WriteLine("m: " + material.Id);
}
}
if (itemsDictionary.ContainsKey(blueprint.Output.Id))
{
blueprint.Output.Name = itemsDictionary[blueprint.Output.Id];
}
else
{
Console.WriteLine("b: " + blueprint.Output.Id);
}
}
}
Definition of the requisite classes follow; they are merely containers for data and I've stripped out all the bits irrelevant to my question:
public class Material
{
public uint Id { get; set; }
public string Name { get; set; }
}
public class Product
{
public uint Id { get; set; }
public string Name { get; set; }
}
public class Blueprint
{
public IDictionary<Material, uint> Input { get; set; }
public Product Output { get; set; }
}
I don't think this is actually a good candidate for conversion to LINQ - at least not in its current form.
Yes, you have a nested foreach loop - but you're doing something else in the top-level foreach loop, so it's not the easy-to-convert form which just contains nesting.
More importantly, the body of your code is all about side-effects, whether that's writing to the console or changing the values within the objects you've found. LINQ is great when you've got a complicated query and you want to loop over that to act on each item in turn, possibly with side-effects... but your queries aren't really complicated, so you wouldn't get much benefit.
One thing you could do is give Blueprint and Product a common interface containing Id and Name. Then you could write a single method to update the products and blueprints via itemsDictionary based on a query for each:
UpdateNames(itemsDictionary, blueprints);
UpdateNames(itemsDictionary, blueprints.SelectMany(x => x.Input.Keys));
...
private static void UpdateNames<TSource>(Dictionary<string, string> idMap,
IEnumerable<TSource> source) where TSource : INameAndId
{
foreach (TSource item in source)
{
string name;
if (idMap.TryGetValue(item.Id, out name))
{
item.Name = name;
}
}
}
This is assuming you don't actually need the console output. If you do, you could always pass in the appropriate prefix and add an "else" block in the method. Note that I've used TryGetValue instead of performing two lookups on the dictionary for each iteration.
I'll be honest, I did not read your code. For me, your question answered itself when you said "code to set the properties." You should not be using LINQ to alter the state of objects / having side effects. Yes, I know that you could write extension methods that would cause that to happen, but you'd be abusing the functional paradigm poised by LINQ, and possibly creating a maintenance burden, especially for other developers who probably won't be finding any books or articles supporting your endeaver.
As you're interested in doing as much as possible with Linq, you might like to try the VS plugin ReSharper. It will identify loops (or portions of loops) that can be converted to Linq operators. It does a bunch of other helpful stuff with Linq too.
For example, loops that sum values are converted to use Sum, and loops that apply an internal filter are changed to use Where. Even string concatenation or other recursion on an object is converted to Aggregate. I've learned more about Linq from trying the changes it suggests.
Plus ReSharper is awesome for about 1000 other reasons as well :)
As others have said, you probably don't want to do it without foreach loops. The loops signify side-effects, which is the whole point of the exercise. That said, you can still LINQ it up:
var materialNames =
from blueprint in blueprints
from material in blueprint.Input.Keys
where itemsDictionary.ContainsKey(material.Id)
select new { material, name = itemsDictionary[material.Id] };
foreach (var update in materialNames)
update.material.Name = update.name;
var outputNames =
from blueprint in blueprints
where itemsDictionary.ContainsKey(blueprint.Output.Id)
select new { blueprint, name = itemsDictionary[blueprint.Output.Id] };
foreach (var update in outputNames)
update.Output.Name = update.name;
What about this
(from blueprint in blueprints
from material in blueprint.Input.Keys
where itemsDictionary.ContainsKey(material.Id)
select new { material, name = itemsDictionary[material.Id] })
.ToList()
.ForEach(rs => rs.material.Name = rs.name);
(from blueprint in blueprints
where itemsDictionary.ContainsKey(blueprint.Output.Id)
select new { blueprint, name = itemsDictionary[blueprint.Output.Id] })
.ToList()
.ForEach(rs => rs.blueprint.Output.Name = rs.name);
See if this works
var res = from blueprint in blueprints
from material in blueprint.Input.Keys
join item in items on
material.Id equals Convert.ToUInt32(item.Attribute("id").Value)
select material.Set(x=> { Name = item.Attribute("id").Value; });
You wont find set method, for that there is an extension method created.
public static class LinqExtensions
{
/// <summary>
/// Used to modify properties of an object returned from a LINQ query
/// </summary>
public static TSource Set<TSource>(this TSource input,
Action<TSource> updater)
{
updater(input);
return input;
}
}

Categories

Resources