Should I replace these nested foreach loops with LINQ, and how? - c#

I receive data from a service in the following format:
public class Foo
{
string Name;
}
public class Bar
{
int ID;
List<Foo> Foos;
}
public class Container
{
List<Bar> Bars;
}
I need to write a method that returns the Names of all of the Foos in a Container, paired with the ID of their associated Bar, in the following class:
public class FooBar
{
int BarID;
Foo Name;
}
This is what I came up with:
IEnumerable<FooBar> FooBars(Container c)
{
foreach (var b in c.Bars)
{
foreach (var f in b.Foos)
{
yield return new FooBar() { BarID = b.ID; Name = f.Name; }
}
}
}
I have two questions:
How would I write this with LINQ instead of nested foreach loops?
Is there any good reason to do so?

This is the query syntax for LINQ's SelectMany, which allows you to do what you're describing. As far as why you would do this, I personally find it more easily readable.
from b in c.Bars
from f in b.Foos
select new FooBar {BarID = b.ID, Name = f.Name};

Related

Using same method on different classes

I'm created a method that separate the data for an SQLite database into 3 categories:
Modified (variables in list_1 that are not equals to the list_2 ones)
Created (variables in list_1 that are not found in list_2)
Deleted (list_2 variables that are not existing anymore in list_1)
sidenote: list_2 is a backup of list_1 before any modification
The problem with this code is that I can use it only on one class. If I want a second class, then I have to write down the same code again with minor changes. I have now 3 classes, but in the future, I probably want more. It'll be pretty time consuming if I try to write down over and over with every single class, so I posted this question for any suggestion. Also because I didn't find any articles where it uses lambda expressions.
public class Stats
{
public int id { get; set; }
public string name { get; set; }
}
public class FactStats : Stats
{
public string tag { get; set; }
public float balance { get; set; }
public FactStats ShallowCopy()
{
return (FactStats)this.MemberwiseClone();
}
}
List<FactStats> Factions = new List<FactStats>();
List<FactStats> SavedFactions = new List<FactStats>();
void SavetoDatabase()
{
//1. Separate Data
List<FactStats> F_JoinedList = new List<FactStats>();
List<int> F_Modify = new List<int>();
List<int> F_Create = new List<int>();
List<int> F_Delete = new List<int>();
//Modified Objects
F_JoinedList = Factions.Where(n => SavedFactions.Any(o => o.id == n.id)).ToList();
foreach (FactStats f in F_JoinedList)
{
FactStats fs = SavedFactions.Single(x => x.id == f.id);
if (!f.CompareEquals(fs))
F_Modify.Add(f.id);
}
//Created Objects
foreach (FactStats f in Factions)
{
bool vane = Convert.ToBoolean(SavedFactions.Where(f2 => f2.id == f.id).Count());
if (!vane)
F_Create.Add(f.id);
}
//Deleted Objects
foreach (FactStats f in SavedFactions)
{
bool vane = Convert.ToBoolean(Factions.Where(f2 => f2.id == f.id).Count());
if (!vane)
F_Delete.Add(f.id);
}
...
}
I've tried to do it with reflection, not much success. Probably because of my lack of experience.
CompareEquals extensive method (at the Modified Objects) is a third party code that compare two objects of the same class using reflection.
The best way to use one method on different classes is to use Generic method. Since classes are different they should conform to the common interface, for example IUniqueIdentifiable should have "id" property.
You need to create method:
void Save<T>(List<T> saved, List<T> modified) where T: IUniqueIdentifiable
{
List<T> F_JoinedList = new List<T>();
List<int> F_Modify = new List<int>();
List<int> F_Create = new List<int>();
List<int> F_Delete = new List<int>();
//Modified Objects
F_JoinedList = modified.Where(n => saved.Any(o => o.id == n.id)).ToList();
foreach (T f in F_JoinedList)
{
T fs = saved.Single(x => x.id == f.id);
if (!f.CompareEquals(fs))
F_Modify.Add(f.id);
}
//Created Objects
foreach (T f in modified)
{
bool vane = Convert.ToBoolean(saved.Where(f2 => f2.id == f.id).Count());
if (!vane)
F_Create.Add(f.id);
}
//Deleted Objects
foreach (T f in saved)
{
bool vane = Convert.ToBoolean(modified.Where(f2 => f2.id == f.id).Count());
if (!vane)
F_Delete.Add(f.id);
}
...
}
public interface IUniqueIdentifiable
{
id {get;}
}
There are tons of articles how to create Generic method, you can find one sample below
http://www.informit.com/articles/article.aspx?p=605369&seqNum=4

Updating an Object from a List in C#

I have the following:
public class Animal
public int currentPopulation
public string name
public Animal(int currentPopulation, string name){
this.currentPopulation = currentPopulation;
this.name = name;
}
In another class I have:
public class MainClass
<List><Animal>animalList
...
lion = newAnimal(100, "Lion");
cat = newAnimal(20, "Cat");
dog = newAnimal(40, "Dog")
animalList.add(lion);
animalList.add(cat);
animalList.add(dog);
Every so often I have to fetch new data from a server and update the animal property, currentPopulation in the MainClass. Currently I'm doing this by the following:
public void UpdatePopulations(int lionPopulation, int catPopulation, int dogPopulation)
foreach(var item in animalList.where(n=>n.name=="Lion")){
item.currentPopulation = lionPopulation;
}
... and the same for the cat and dog.
I feel like my solution is bulky and I'm wondering if there is a cleaner way to update the objects from the list.
When working with list (which is a dynamic container) there is no way to find element without iterating over it.
One way you can make it more efficient is updating your List in one path and not using LINQ to find elements.
Something like this
foreach(vat animal in animalList)
{
if (animal.name == "Lion")
animal.currentPopulation = ...
else if (animal.name == "...")
animal.currentPopulation = ...
}
I'd suggest you use different data container than list.
Dictionary<string, Animal> animals will serve you better because than you can use animal name as update keys.
You can also differentiate with the help of 'enum' as shown below but you need to iterate through list to identify animal.
public enum AnimalName
{
Lion,
Cat,
Dog
}
public class Animal
{
public AnimalName Name { get; set; }
public int Population { get; set; }
public Animal(AnimalName name, int population)
{
Name = name;
Population = population;
}
}
public void UpdatePopulations(int lionPopulation, int catPopulation, int dogPopulation)
{
foreach (var animal in animals)
{
switch (animal.Name)
{
case AnimalName.Lion:
animal.Population = lionPopulation;
break;
case AnimalName.Cat:
animal.Population = catPopulation;
break;
case AnimalName.Dog:
animal.Population = dogPopulation;
break;
}
}
}
There is almost no benefit to convert the animalList to Dictionary, if you are going to update all of the animals anyway. Some improvement that I can think of is to accept IEnumerable instead, so you can freely update certain or all animals.
public void UpdatePopulations(IEnumerable<Animal> newAnimals)
{
var dictionary = newAnimals.ToDictionary<string, int>(a=>a.Name, a=>a.currentPopulation); // convert to dictionary, so that we have O(1) lookup during the search later. This process itself is O(n)
foreach(var animal in animalList) // this will be O(n)
{
if(dictionary.ContainsKey(animal.Name))
{
animal.currentPopulation = dictionary[animal.Name].currentPopulation;
}
}
}
public void UpdatePopulations(Dictionary<string, int> populations)
{
foreach(var population in populations)
foreach(var animal in animalList.Where(x => x.name == population.Key))
animal.currentPopulation = population.Value;
}
Usage:
variableName.UpdatePopulations(new Dictionary<string, int> {
["Lion"] = 1000,
["Cat"] = 2000,
["Dog"] = 3000
});

Need help to understand polymorphism

The classes below consist of
A - father class
B - Child class
Holder - Contains a list of A's
I want to reach a child property from the list of fatherobjects. Why cant I do this? Or better question, how do I do this?
public class A
{
public int var = 0;
}
public class B : A
{
public int Property1 { get; set; }
public int Property2 { get; set; }
public B()
{
}
public B(B p_B)
{
Property1 = p_B.Property1;
Property2 = p_B.Property2;
}
}
class Holder
{
private List<A> m_Objects = new List<A>();
public void AddObject(A p_Object)
{
m_Objects.Add(p_Object);
}
public void AddObjectProperty1(B p_B)
{
// At this point, m_Objects holds a B-object. And I want to add the value from Property1
// but there is no Property1 in the A-class so I cant do this. How do I use the base.values from
// a statement like the one below?
int index = m_Objects.FindIndex(item => item.Property1 == p_B.Property1);
if (index > -1)
m_Objects.ElementAt(index).Property1 += p_B.Property1;
}
}
class Program
{
static void Main(string[] args)
{
// Class to hold the objects
Holder h = new Holder();
// Create a B object
B b = new B();
b.Property1 = 1;
b.Property2 = 2;
// Place a new instance of the B-object in a list of A's
h.AddObject(new B(b));
// Add the value from Property1 to the value in the b-object in the a-list. :P
h.AddObjectProperty1(b);
Console.WriteLine(++b.var);
Console.ReadLine();
}
}
You can use type casting:
(m_Objects[i] as B).Property1
Or
((B)m_Objects[i]).Property1
At compile-time there is no possibility for the compiler to know, you would only add Bs to your list of As. So there is no guarantee whatsoever that each item in the following query is an instance of B and thus has Property1
int index = m_Objects.FindIndex(item => item.Property1 == p_B.Property1);
First possibilty is casting as in Artyom's answer. But this will fail if you not all of the elements in the List are really Bs. So if you rely on all Elements in m_Objects to be instances of B, why don't you just use List<B> m_Objects?
If you need the mixed list, you have to do a type-check in the query to ensure, you are dealing with an instance of Bbefore casting.
int index = m_Objects.FindIndex(item => (item is B) && (item as B).Property1 == p_B.Property1);
See this DotNetFiddle Example

Why IEnumerable<T> becomes empty after adding elements to a collection?

I have an IEnumerable<T> when I iterate through it and add it's element to a list it becomes empty?
Is there generally anything wrong about what I expect from the code?
public class Apple
{
private ICollection<Fruit> _fruits = new List<Fruit>();
public void AddFruits(IEnumerable<Fruit> fruits)
{
if (fruits == null) throw new ArgumentNullException("fruits");
foreach (var fruit in fruits)
{
_fruits.Add(fruit);
}
}
}
The caller code:
public void AddFruits(IEnumerable<Fruit> fruitsToAdd)
{
foreach (var apple in apples)
{
// Here fruitsToAdd has elements, fruitsToAdd.ToList() has two fruits.
apple.AddFruits(fruitsToAdd);
// Here fruitsToAdd has NO element!!, fruitsToAdd.ToList() is empty!
// next iteration will not add any fruit to next apple since fruitsToAdd is empty.
}
}
Update
The ToList() solved the problem. The root of the problem was that the caller to AddFruits(IEnumerable fruitsToAdd) send fruitsToAdd that was like.
fruitsToAdd = obj.Fruits.Except(apples.Fruits);
Each time IEnumerable fruitsToAdd was Rest it run above statement. Which at next iteration run Except and thereby returned no fruits.
The right way is fruitsToAdd = obj.Fruits.Except(apples.Fruits).ToList(); Since we want one evaluation.
Ok, try this:
public void AddFruits(IEnumerable<Fruit> fruitsToAdd)
{
var fruitsToAddCopy = fruitsToAdd.ToList(); // add just this line
foreach (var apple in apples)
{
apple.AddFruits(fruitsToAddCopy); // and change this
}
}
Without knowing the origin of your fruitsToAdd it's impossible to say more. Some IEnumerable<> can't be re-used. Others can.
I modified your code to get it to compile and wrote a test. Your list does not become empty after copying it's elements into the apples.
using System;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace ClassLibrary3
{
[TestClass]
public class Class1
{
[TestMethod]
public void test()
{
var fruits = new List<Fruit> {new Fruit(), new Fruit(), new Fruit()};
var lists = AddFruits(fruits);
Assert.IsTrue(fruits.Count == 3);
}
public List<Apple> AddFruits(IEnumerable<Fruit> fruitsToAdd)
{
var apples = new List<Apple>
{
new Apple(),
new Apple()
};
foreach (var apple in apples)
{
apple.AddFruits(fruitsToAdd);
}
return apples;
}
}
public class Fruit
{
}
public class Apple
{
private ICollection<Fruit> _fruits = new List<Fruit>();
public void AddFruits(IEnumerable<Fruit> fruits)
{
if (fruits == null) throw new ArgumentNullException("fruits");
foreach (var fruit in fruits)
{
_fruits.Add(fruit);
}
}
}
}
The code in your question shouldn't exhibit such behavior, so I am presuming you tried to simplify it, but removed a lot of functionality from it.
What looks a bit suspicious is that your _fruits field is of type ICollection<T>. This interface is often used with custom collection implementations. Is it possible that, in the actual code, this field isn't instantiated with a List<T>, but rather with a custom implementation of that interface?
If you have a custom collection implementation, then it is perfectly possible for its Add method to do weird stuff (like removing an item from its previous "parent" collection before adding it to its new "parent"). Tree collections often do such things to simplify moving nodes around.
[Edit]
I am aware that this is not OPs actual problem, but I will nevertheless add an example to demonstrate that a custom collection implementation can in fact modify the input collection when its members are added to a different collection.
Let's say the Fruit class looks like this:
partial class Fruit
{
private ICollection<Fruit> _children;
private Fruit _parent;
public String Name { get; set; }
public Fruit()
{
_children = new FruitCollection(this);
}
public void AddFruits(IEnumerable<Fruit> fruits)
{
foreach (Fruit f in fruits)
_children.Add(f);
}
public int NumberOfChildren
{
get { return _children.Count; }
}
public IEnumerable<Fruit> GetFruits()
{
return _children.ToList();
}
}
And there is a custom collection defined as:
partial class Fruit
{
public class FruitCollection : Collection<Fruit>
{
private readonly Fruit _parent;
public FruitCollection(Fruit parent)
{
_parent = parent;
}
protected override void InsertItem(int index, Fruit item)
{
// item already has a parent?
if (item._parent != null)
{
// remove it from previous parent
item._parent._children.Remove(item);
}
// set the new parent
item._parent = _parent;
base.InsertItem(index, item);
}
// other methods should be overriden in a similar way
}
}
Then the following program:
static void Main(string[] args)
{
List<Fruit> abc = new List<Fruit>()
{
new Fruit() { Name = "a" },
new Fruit() { Name = "b" },
new Fruit() { Name = "c" }
};
Fruit apple = new Fruit() { Name = "apple" };
apple.AddFruits(abc);
Console.WriteLine("{0} has {1} children", apple.Name, apple.NumberOfChildren);
// now try to add apples's children to
// each of the following fruits
List<Fruit> def = new List<Fruit>()
{
new Fruit() { Name = "d" },
new Fruit() { Name = "e" },
new Fruit() { Name = "f" }
};
foreach (Fruit f in def)
{
f.AddFruits(apple.GetFruits());
Console.WriteLine("{0} has {1} children", f.Name, f.NumberOfChildren);
}
Console.Read();
}
Would print:
apple has 3 children
d has 3 children
e has 0 children
f has 0 children
Because apple.GetFruits() will return 0 after the first iteration.
By looking at the custom collection's source, it is hard to realize that _children.Add(f) in AddFruits in fact modifies the fruits previous parent collection.

How to compare two distinctly different objects with similar properties

This is all in C#, using .NET 2.0.
I have two lists of objects. They are not related objects, but they do have certain things in common that can be compared, such as a GUID-based unique identifier. These two lists need to be filtered by another list which just contains GUIDs which may or may not match up with the IDs contained in the first two lists.
I have thought about the idea of casting each object list to just object and sorting by that, but I'm not sure that I'll be able to access the ID property once it's cast, and I'm thinking that the method to sort the two lists should be somewhat dumb in knowing what the list to be sorted is.
What would be the best way to bring in each object list so that it can be sorted against the list with only the IDs?
You should make each of your different objects implement a common interface. Then create an IComparer<T> for that interface and use it in your sort.
Okay, if you have access to modify your original classes only to add the interface there, Matthew had it spot on. I went a little crazy here and defined out a full solution using 2.0 anonymous delegates. (I think I'm way addicted to 3.0 Lambda; otherwise, I probably would've written this out in foreach loops if I was using 2005 still).
Basically, create an interface with the common properties. Make yoru two classes implement the interface. Create a common list casted as the interface, cast and rip the values into the new list; remove any unmatched items.
//Program Output:
List1:
206aa77c-8259-428b-a4a0-0e005d8b016c
64f71cc9-596d-4cb8-9eb3-35da3b96f583
List2:
10382452-a7fe-4307-ae4c-41580dc69146
97f3f3f6-6e64-4109-9737-cb72280bc112
64f71cc9-596d-4cb8-9eb3-35da3b96f583
Matches:
64f71cc9-596d-4cb8-9eb3-35da3b96f583
Press any key to continue . . .
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication8
{
class Program
{
static void Main(string[] args)
{
//test initialization
List<ClassTypeA> list1 = new List<ClassTypeA>();
List<ClassTypeB> list2 = new List<ClassTypeB>();
ClassTypeA citem = new ClassTypeA();
ClassTypeB citem2 = new ClassTypeB();
citem2.ID = citem.ID;
list1.Add(new ClassTypeA());
list1.Add(citem);
list2.Add(new ClassTypeB());
list2.Add(new ClassTypeB());
list2.Add(citem2);
//new common list.
List<ICommonTypeMakeUpYourOwnName> common_list =
new List<ICommonTypeMakeUpYourOwnName>();
//in english, give me everything in list 1
//and cast it to the interface
common_list.AddRange(
list1.ConvertAll<ICommonTypeMakeUpYourOwnName>(delegate(
ClassTypeA x) { return (ICommonTypeMakeUpYourOwnName)x; }));
//in english, give me all the items in the
//common list that don't exist in list2 and remove them.
common_list.RemoveAll(delegate(ICommonTypeMakeUpYourOwnName x)
{ return list2.Find(delegate(ClassTypeB y)
{return y.ID == x.ID;}) == null; });
//show list1
Console.WriteLine("List1:");
foreach (ClassTypeA item in list1)
{
Console.WriteLine(item.ID);
}
//show list2
Console.WriteLine("\nList2:");
foreach (ClassTypeB item in list2)
{
Console.WriteLine(item.ID);
}
//show the common items
Console.WriteLine("\nMatches:");
foreach (ICommonTypeMakeUpYourOwnName item in common_list)
{
Console.WriteLine(item.ID);
}
}
}
interface ICommonTypeMakeUpYourOwnName
{
Guid ID { get; set; }
}
class ClassTypeA : ICommonTypeMakeUpYourOwnName
{
Guid _ID;
public Guid ID {get { return _ID; } set { _ID = value;}}
int _Stuff1;
public int Stuff1 {get { return _Stuff1; } set { _Stuff1 = value;}}
string _Stuff2;
public string Stuff2 {get { return _Stuff2; } set { _Stuff2 = value;}}
public ClassTypeA()
{
this.ID = Guid.NewGuid();
}
}
class ClassTypeB : ICommonTypeMakeUpYourOwnName
{
Guid _ID;
public Guid ID {get { return _ID; } set { _ID = value;}}
int _Stuff3;
public int Stuff3 {get { return _Stuff3; } set { _Stuff3 = value;}}
string _Stuff4;
public string Stuff4 {get { return _Stuff4; } set { _Stuff4 = value;}}
public ClassTypeB()
{
this.ID = Guid.NewGuid();
}
}
}
Using only .NET 2.0 methods:
class Foo
{
public Guid Guid { get; }
}
List<Foo> GetFooSubset(List<Foo> foos, List<Guid> guids)
{
return foos.FindAll(foo => guids.Contains(foo.Guid));
}
If your classes don't implement a common interface, you'll have to implement GetFooSubset for each type individually.
I'm not sure that I fully understand what you want, but you can use linq to select out the matching items from the lists as well as sorting them. Here is a simple example where the values from one list are filtered on another and sorted.
List<int> itemList = new List<int>() { 9,6,3,4,5,2,7,8,1 };
List<int> filterList = new List<int>() { 2, 6, 9 };
IEnumerable<int> filtered = itemList.SelectMany(item => filterList.Where(filter => filter == item)).OrderBy(p => p);
I haven't had a chance to use AutoMapper yet, but from what you describe you wish to check it out. From Jimmy Bogard's post:
AutoMapper conventions
Since AutoMapper flattens, it will
look for:
Matching property names
Nested property names (Product.Name
maps to ProductName, by assuming a
PascalCase naming convention)
Methods starting with the word “Get”,
so GetTotal() maps to Total
Any existing type map already
configured
Basically, if you removed all the
“dots” and “Gets”, AutoMapper will
match property names. Right now,
AutoMapper does not fail on mismatched
types, but for some other reasons.
I am not totally sure what you want as your end results, however....
If you are comparing the properties on two different types you could project the property names and corresponding values into two dictionaries. And with that information do some sort of sorting/difference of the property values.
Guid newGuid = Guid.NewGuid();
var classA = new ClassA{Id = newGuid};
var classB = new ClassB{Id = newGuid};
PropertyInfo[] classAProperties = classA.GetType().GetProperties();
Dictionary<string, object> classAPropertyValue = classAProperties.ToDictionary(pName => pName.Name,
pValue =>
pValue.GetValue(classA, null));
PropertyInfo[] classBProperties = classB.GetType().GetProperties();
Dictionary<string, object> classBPropetyValue = classBProperties.ToDictionary(pName => pName.Name,
pValue =>
pValue.GetValue(classB, null));
internal class ClassB
{
public Guid Id { get; set; }
}
internal class ClassA
{
public Guid Id { get; set; }
}
classAPropertyValue
Count = 1
[0]: {[Id, d0093d33-a59b-4537-bde9-67db324cf7f6]}
classBPropetyValue
Count = 1
[0]: {[Id, d0093d33-a59b-4537-bde9-67db324cf7f6]}
Thist should essentially get you what you want - but you may be better of using linq
class T1
{
public T1(Guid g, string n) { Guid = g; MyName = n; }
public Guid Guid { get; set; }
public string MyName { get; set; }
}
class T2
{
public T2(Guid g, string n) { ID = g; Name = n; }
public Guid ID { get; set; }
public string Name { get; set; }
}
class Test
{
public void Run()
{
Guid G1 = Guid.NewGuid();
Guid G2 = Guid.NewGuid();
Guid G3 = Guid.NewGuid();
List<T1> t1s = new List<T1>() {
new T1(G1, "one"),
new T1(G2, "two"),
new T1(G3, "three")
};
List<Guid> filter = new List<Guid>() { G2, G3};
List<T1> filteredValues1 = t1s.FindAll(delegate(T1 item)
{
return filter.Contains(item.Guid);
});
List<T1> filteredValues2 = t1s.FindAll(o1 => filter.Contains(o1.Guid));
}
}

Categories

Resources