Determine Hierarchy Integer from Parent Field C# - c#

I need to determine the hierarchy level to display a tree, I don't need to link relationships at the moment, I have a list of objects as follows:
public class ObjectData
{
public string ID;
public string hierarchyParent;
public int hierarchyLevel;
}
I need to set the hierarchyLevel integer based on its row level. The hierarchyParent var contains the ID of its parent. I don't know how wide each column would be nor how many rows, so it needs to be dynamic with the hierarchy level integer either ascending or descending. So far, I have been able to determine the top row but am unsure how to continue, any help would be appreciated! So far:
List<ObjectData> Sort(List<ObjectData> objectToBeSorted){
List<ObjectData> returnlist = new List<ObjectData>();
string topObject = null;
foreach(ObjectData obj in objectToBeSorted)
{
if(obj.hierarchyParent == null){
topObject = obj.ID;
obj.hierarchyLevel = 1;
}
}
foreach(ObjectData obj in objectToBeSorted)
{
if(obj.hierarchyParent == topObject){
}
}
return returnlist;
}

Here's a quick try with sample data and recursive calls :
The useful part is is in AssignChild method.
public class ObjectData
{
public string ID;
public string hierarchyParent;
public int hierarchyLevel;
}
void Main()
{
var objects = new List<ObjectData>() {
new ObjectData() { ID = "Obj12", hierarchyParent = null },
new ObjectData() { ID = "Obj5", hierarchyParent = "Obj12" },
new ObjectData() { ID = "Obj9", hierarchyParent = "Obj12" },
new ObjectData() { ID = "Obj7", hierarchyParent = "Obj5" },
new ObjectData() { ID = "Obj99", hierarchyParent = "Obj58" },
new ObjectData() { ID = "Obj58", hierarchyParent = "Obj5" } };
ObjectData top = objects.Find(p => p.hierarchyParent == null);
top.hierarchyLevel = 1;
AssignChild(objects, top);
objects.Dump();
}
void AssignChild(List<ObjectData> all, ObjectData parent)
{
var child = all.FindAll(o => o.hierarchyParent == parent.ID);
child.ForEach(c => { c.hierarchyLevel = parent.hierarchyLevel +1; AssignChild(all, c); });
}
It can probably be optimized but it should work.

I suggest doing something like this:
public int GetHierarchyLevel(ObjectData obj, IEnumerable<ObjectData> allObjects)
{
if(obj.hierarchyParent == null)
return 1;
else
return 1 + GetHierarchyLevel(allObjects.First(o=>o.ID == obj.hierarchyParent));
}
Of course, you should integrate this into your classes so that you can possibly replace the arguments by class members. Also, please notice that some error checking may be required. It is just meant to give you an idea of an algorithm.
For performance, I suggest a caching mechanism. Like initializing hierarchyLevel to -1 and using the following modification:
public int GetHierarchyLevel(ObjectData obj, IEnumerable<ObjectData> allObjects)
{
if (obj.hierarchyLevel != -1)
return obj.hierarchyLevel;
if(obj.hierarchyParent == null)
return 1;
else
return 1 + GetHierarchyLevel(allObjects.First(o=>o.ID == obj.hierarchyParent));
}
Of course, this would require invalidating all cached results when you want to recalculate after a change in the structure of your hierarchy.

Related

unit test case returning null while unit testing

I have a below method which simply unnest the list within list and and create merged record all sub lists
e.g.
testResultDTO similar to
{
dept_name :'',
dept_id:'',
personList :'<List>'
}
personList is list similat to
{
first_name :'',
Last_name:'',
workHistList:'<List>'
}
workHistList is similar to
{
task_name:'',
task_description:''}
`
And the method is below
public async Task<FileDTO> GetWorkList(InputParameter inputParameter)
{
TestResultDTO testResultDTO = await GetPersonWorkList(inputParameter);
var testDto = new List<TestDto>();
if (testResultDTO != null)
{
testDto = personWorkFile(testResultDTO);
}
return testDto;
}
The problem is in method personWorkFile
private List<testDTO> personWorkFile(testResultDTO testResultDTO)
{
List<testDTO> testDTO = new List<testDTO>();
if (testResultDTO.workList is null) return new();
foreach (var testItem in testResultDTO.workList)
{
if (testItem.personList != null && testItem.personList.Any())
{
for (var j = 0; j < testItem.personList.Count; j++)
{
List<testDTO> testDTOTemp = new List<testDTO>();
for (var i = 0; i < testItem.personList[j].workHistList.Count; i++)
{
testDTOTemp.Insert(i, mapper.Map(testItem.personList[j].workHistList[i], mapper.Map<testDTO>(testItem.personList[j])));
}
testDTO.AddRange(testDTOTemp);
}
}
}
return testDTO;
}
`
what it does is it create a finale list with record similar to
{dept_name,dept_id,first_name, last_name, task_name, task_description}
Now when i create a unit test for it, it always fail because, it always insert null in list testDTOTemp.insert
my content of test case code is below
mapperMock.Setup(m => m.Map<List<TestResultDTO>, List<TestDTO>>(testResultDTO)).Returns(testDTO);
//call actual service
var result = await workService.GetWorkList(inputParameter);
Can someone please help me understand why it is not able to insert any data testDTOTemp list
The mock replays the setup by matching the method arguments. In this particular case, it will try to match the method call with the specified instance of TestResultDTO.
Override the Equals() method in TestResultDTO to let the mock compare the argument in order to return as per the setup.
Ex:
public class TestResultDTO
{
public int Id {get; set;}
}
var dto01 = new TestResultDTO(){Id = 1};
var dto02 = new TestResultDTO(){Id = 1};
dto01.Equals(dto02); // This will result in false in spite of having same Ids
If the above class is modified to
public class TestResultDTO
{
public int Id {get; set;}
public override bool Equals(object other)
{
var right = other as TestResultDTO;
if(right == null) return false;
var left = this;
var result = left.Id == right.Id;
return result;
}
}
var dto01 = new TestResultDTO(){Id = 1};
var dto02 = new TestResultDTO(){Id = 1};
dto01.Equals(dto02); // This will result in true

How to save values of the GET method in an array and then accessing specific values

I need to access all the items that I have in my database and analyse each one of them. I was thinking I could save all the values into an array and then accessing them loke this:
var ocorrenciasLista = GetOcorrencias().ToArray();
for (int i = 0; i <= ocorrenciasLista.Length; i++)
{
var latitude2 = ocorrenciasLista[i][2];
}
EDIT:
Here is my GetOcorrencias()
[HttpGet]
public IEnumerable<Ocorrencias> GetOcorrencias()
{
int duracao = 2;
DateTime dataDuracao = DateTime.Now.Subtract(new TimeSpan(0, duracao, 0, 0));
var ocorrencias = _context.Ocorrencias
.Where(e => (e.Estado == Ocorrencias.EstadoOcorrencia.emAvaliacao && e.DataOcorrencia >= dataDuracao) ||
e.Estado == Ocorrencias.EstadoOcorrencia.aceite);
return ocorrencias;
}
I get an error saying "Cannot apply indexing with [] to an expression of type Ocorrencias". Ocorrencias is my main model.
In the code above I want to access the latitude of every item that is on my database. How should I do this?
If you want your method to return an IEnumerable you have to do something like this:
Say this is your class:
public class SomeClass
{
public string Name { get; set; }
}
And change the return type of your GetOcorrencias() to the following. I have a sample method here:
static IEnumerable<SomeClass[]> GetOcorrencias()
{
var data = new SomeClass[2][];
data[0] = new SomeClass[1] { new SomeClass() { Name = "A" } };
data[1] = new SomeClass[1] { new SomeClass() { Name = "B" } };
return data;
}
Now you can access it like a jagged array in your main:
var data = GetOcorrencias().ToArray();
for (int i = 0; i < data.Length; i++)
{
var datai = data[i][0];
}

c#: collections with unique elements

Is there a collection in C# that guarantees me that I will have only unique elements? I've read about HashSet, but this collection can contain duplicates. Here is my code:
public class Bean
{
public string Name { get; set; }
public int Id { get; set; }
public override bool Equals(object obj)
{
var bean = obj as Bean;
if (bean == null)
{
return false;
}
return this.Name.Equals(bean.Name) && this.Id == bean.Id;
}
public override int GetHashCode()
{
return Name.GetHashCode() * this.Id.GetHashCode();
}
}
You may complain about using non-readonly properties in my GetHashCode method, but this is a way of doing (not the right one).
HashSet<Bean> set = new HashSet<Bean>();
Bean b1 = new Bean {Name = "n", Id = 1};
Bean b2 = new Bean {Name = "n", Id = 2};
set.Add(b1);
set.Add(b2);
b2.Id = 1;
var elements = set.ToList();
var elem1 = elements[0];
var elem2 = elements[1];
if (elem1.Equals(elem2))
{
Console.WriteLine("elements are equal");
}
And in this case, my set contains duplicates.
So is there a collection in C# that guarantees me that it does not contains duplicates?
So is there a collection in C# that guarantees me that it does not
contains duplicates?
There is no existing collection class in C# that does this. You could write your own, but there is no existing one.
Some extra information regarding the issue you are experiencing
If you change a HashSet entry after adding it to the HashSet, then you need to regenerate the HashSet. My below RegenerateHashSet can be used to do that.
The reason you need to regenerate is that duplicate detection only occurs at insertion time (or, in other words, it relies on you not changing an object after you insert it). Which makes sense, if you think about it. The HashSet has no way to detect that an object it contains has changed.
using System;
using System.Collections.Generic;
using System.Linq;
namespace Test
{
public static class HashSetExtensions
{
public static HashSet<T> RegenerateHashSet<T>(this HashSet<T> original)
{
return new HashSet<T>(original, original.Comparer);
}
}
public class Bean
{
public string Name { get; set; }
public int Id { get; set; }
public override bool Equals(object obj)
{
var bean = obj as Bean;
if (bean == null)
{
return false;
}
return Name.Equals(bean.Name) && Id == bean.Id;
}
public override int GetHashCode()
{
return Name.GetHashCode() * Id.GetHashCode();
}
}
public class Program
{
static void Main(string[] args)
{
HashSet<Bean> set = new HashSet<Bean>();
Bean b1 = new Bean { Name = "n", Id = 1 };
Bean b2 = new Bean { Name = "n", Id = 2 };
set.Add(b1);
set.Add(b2);
b2.Id = 1;
var elements = set.ToList();
var elem1 = elements[0];
var elem2 = elements[1];
if (elem1.Equals(elem2))
{
Console.WriteLine("elements are equal");
}
Console.WriteLine(set.Count);
set = set.RegenerateHashSet();
Console.WriteLine(set.Count);
Console.ReadLine();
}
}
}
Note that the above technique is not bullet-proof - if you add two objects (Object A and Object B) which are duplicates and then change Object B to be different to Object A then the HashSet will still only have one entry in it (since Object B was never added). As such, what you probably want to do is actually store your complete list in a List instead, and then use new HashSet<T>(yourList) whenever you want unique entries. The below class may assist you if you decide to go down that route.
public class RecalculatingHashSet<T>
{
private List<T> originalValues = new List<T>();
public HashSet<T> GetUnique()
{
return new HashSet<T>(originalValues);
}
public void Add(T item)
{
originalValues.Add(item);
}
}
If you don't write your own collection type and handle property changed events to re-evaluate the items, you need to re-evaluate the items at each access. This can be accomplished with LINQ deferred execution:
ICollection<Bean> items= new List<Bean>();
IEnumerable<Bean> reader = items.Distinct();
Rule: only use items to insert or remove elements, use reader for any read access.
Bean b1 = new Bean { Name = "n", Id = 1 };
Bean b2 = new Bean { Name = "n", Id = 2 };
items.Add(b1);
items.Add(b2);
b2.Id = 1;
var elements = reader.ToList();
var elem1 = elements[0];
var elem2 = elements[1]; // throws exception because there is only one element in the result list.

Comparing two lists and return not matching items results with error

I tried to compare two lists by using the Except method. But when I did, I got an error saying:
Cannot convert from 'Systems.Collections.Generic.List<>' to 'System.Linq.IQueryable<>'
'System.Collections.Generic.List<> does not contain a definition for 'Except' and the best extension method overload 'System.Linq.Queryable.Except(System.Linq.IQueryable, System.Collections.GEneric.IEnumerable)' has some invalid arguments
I also experienced this when I tried Intersect. I'm trying to compare Sent list and Result list (code and list shown below) and return items that does not have any match. So when I googled for how to do so, I came across the Except method as well as the Intersect.
public class Sent
{
public string Address;
public string Data;
}
public class Result
{
public string AddressOK;
public string DataOK;
}
var sent = new List<Sent>();
sent.Add(new Sent() { Address = linaddr1, Data = lindat1 });
var res = new List<Result>();
res.Add( new Result() { AddressOK = linaddr2, DataOK = lindat2 } );
//linaddr1 and 2, lindat1 and 2 contains the address and data shown in the list below
//taken from another part of the entire program
The lists look like such:
sent res
Address Data Address Data
04004C 55AA55 04004C 55AA55
040004 0720 040004 0720
040037 30
04004A FFFF 04004A FFFF
I only tried using this code:
var diff = sent.Except(res).ToList()
but as I've mentioned, it results with the aforementioned errors above.
EDIT: I edited the list. Sorry for that. It's just only a matter of the res list missing one or two or more items from the original list and then comparing both lists to see which item/s is/are missing from the res list.
Use Any:
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main()
{
var sent = new List<Sent>()
{
new Sent { Address = "04004C", Data = "55AA55" },
new Sent { Address = "040004", Data = "0720" },
new Sent { Address = "040037", Data = "31" },
new Sent { Address = "04004A", Data = "FFFF" }
};
var res = new List<Result> () {
new Result { AddressOK = "04004C", DataOK = "55AA55" },
new Result { AddressOK = "040004", DataOK = "0721" },
new Result { AddressOK = "040038 ", DataOK = "31" },
new Result { AddressOK = "04004A", DataOK = "FFFF" }
};
var diff =
sent.Where (s => !res.Any (r => s.Address == r.AddressOK && s.Data == r.DataOK ));
foreach (var item in diff)
{
Console.WriteLine("{0} {1}", item.Address, item.Data);
}
}
}
public class Sent
{
public string Address;
public string Data;
}
public class Result
{
public string AddressOK;
public string DataOK;
}
Output:
040004 0720
040037 31
Live Code: https://dotnetfiddle.net/ZVuiPd
The types Sent and Result are distinct types, but sent.Except(res) expects them to be the same. That's your first mistake.
The following is a simple (but incorrect) fix:
var diff =
sent
.Except(res.Select(x => new Sent() { Address = x.AddressOK, Data = x.DataOK }))
.ToList();
Even though this compiles, and runs, it doesn't remove the duplicates because your Sent doesn't override GetHashCode and Equals, hence it only compares references and not the actual properties.
You can either implement GetHashCode and Equals, or create an IEqualityComparer<Sent> to get this to work.
An IEqualityComparer<Sent> implementation might look like this:
public class SentEqualityComparer : IEqualityComparer<Sent>
{
public int GetHashCode(Sent sent)
{
return sent.Address.GetHashCode() ^ sent.Data.GetHashCode();
}
public bool Equals(Sent left, Sent right)
{
return (left.Address == right.Address) && (left.Data == right.Data);
}
}
And you would use it like so:
var diff =
sent
.Except(
res.Select(x => new Sent() { Address = x.AddressOK, Data = x.DataOK }),
new SentEqualityComparer())
.ToList();
This works as you expect.
The other option, to override GetHashCode and Equals, comes with an additional hurdle. The result of GetHashCode should not ever change throughout the lifetime of the object otherwise you can't use the object in a dictionary or any other data structure that relies on the hash code.
So, to make it work, you need to change Address & Data to be read-only.
Here is an implementation of your Sent class that will work correctly:
public sealed class Sent : IEquatable<Sent>
{
private readonly string _Address;
private readonly string _Data;
public string Address { get { return _Address; } }
public string Data { get { return _Data; } }
public Sent(string Address, string Data)
{
_Address = Address;
_Data = Data;
}
public override bool Equals(object obj)
{
if (obj is Sent)
return Equals((Sent)obj);
return false;
}
public bool Equals(Sent obj)
{
if (obj == null) return false;
if (!EqualityComparer<string>.Default.Equals(_Address, obj._Address)) return false;
if (!EqualityComparer<string>.Default.Equals(_Data, obj._Data)) return false;
return true;
}
public override int GetHashCode()
{
int hash = 0;
hash ^= EqualityComparer<string>.Default.GetHashCode(_Address);
hash ^= EqualityComparer<string>.Default.GetHashCode(_Data);
return hash;
}
}
If you are comfortable using an AOP component to automate the manual code of implementing IEquatable, another approach would be is to use Equals.Fody:
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main()
{
var a = new Sent { Address = "04004C", Data = "55AA55" };
var b = new Sent { Address = "04004C", Data = "55AA55" };
Console.WriteLine(a.Equals(b)); // True with use of an AOP, False with no AOP
var sent = new List<Sent>() {
new Sent { Address = "04004C", Data = "55AA55" },
new Sent { Address = "040004", Data = "0720" },
new Sent { Address = "040037", Data = "31" },
new Sent { Address = "04004A", Data = "FFFF" }
};
var res = new List<Result>() {
new Result { AddressOK = "04004C", DataOK = "55AA55" },
new Result { AddressOK = "040004", DataOK = "0721" },
new Result { AddressOK = "040038 ", DataOK = "31" },
new Result { AddressOK = "04004A", DataOK = "FFFF" }
};
var diff =
sent.Except(
res.Select(r => new Sent { Address = r.AddressOK, Data = r.DataOK })
);
foreach (var item in diff)
Console.WriteLine("{0} {1}", item.Address, item.Data);
}
}
[Equals]
public class Sent
{
public string Address;
public string Data;
[CustomEqualsInternal]
bool CustomLogic(Sent other)
{
return other.Address == this.Address && other.Data == this.Data;
}
}
public class Result
{
public string AddressOK;
public string DataOK;
}
Output:
True
040004 0720
040037 31
If you'll do map Result to Sent very often, you can further shorten your Linq query code to..
var diff = sent.Except(res.Select(r => (Sent)r));
..by automating the mapping of Result to Sent, use implicit operator:
[Equals]
public class Sent
{
public string Address;
public string Data;
[CustomEqualsInternal]
bool CustomLogic(Sent other)
{
return other.Address == this.Address && other.Data == this.Data;
}
public static implicit operator Sent(Result r)
{
return new Sent { Address = r.AddressOK, Data = r.DataOK };
}
}
#Kurisuchin
Suppose you have 2 list and in both you have ID property based on which you want to compare both list and want to store non matching item in third list.
In this Situation following Linq Query can help out.
var result = List2.Where(p => !List1.Any(p2 => p2.ID == p.ID)).ToList();

Refactoring WPF code behind

I have a method called get Data which executes my SQL and returns some rows of ContactLists containing Aggregated Labels.At the moment this method is in my code behind and would like to move it to a separate Data Access class. I would appreciate your assistance. Thanks!
Is normal, if i understand your code, you do this operation after ContactList initialization:
contactList.Labels = new ObservableCollection<Label>()
{
new Label() {
Name = dr["LABEL_NAME"].ToString(),
Count = Convert.ToInt32(dr["LABEL_COUNT"])
}
};
For each ContactList is always added one item, you will do something like this:
contactList.Labels = new ObservableCollection<Label>();
foreach(var item in <yourLabelDataSource>)
contactList.Labels.Add(new Label(...));
The solution is like this:
Dictionary<int, ContactList> myContactDictionary = new Dictionary<int, ContactList>();
using (DB2DataReader dr = command.ExecuteReader())
{
while (dr.Read())
{
int id = Convert.ToInt32(dr["CONTACT_LIST_ID"]);
if (!myContactDictionary.ContainsKey(id))
{
ContactList contactList = new ContactList();
contactList.ContactListID = id;
contactList.ContactListName = dr["CONTACT_LIST_NAME"].ToString();
contactList.Labels = new ObservableCollection<Label>()
{
new Label()
{
Name = dr["LABEL_NAME"].ToString(),
Count = Convert.ToInt32(dr["LABEL_COUNT"])
}
};
myContactDictionary.Add(id, contactList);
}
else
{
//Add new label because CONTACT_LIST_ID Exists
ContactList contactList = myContactDictionary[id];
contactList.Labels.Add(
new Label()
{
Name = dr["LABEL_NAME"].ToString(),
Count = Convert.ToInt32(dr["LABEL_COUNT"])
}
);
}
}
}
Ben, for your last question you can use this solution:
else
{
//Add new label because CONTACT_LIST_ID Exists
ContactList contactList = myContactDictionary[id];
string name = dr["LABEL_NAME"].ToString();
var label = contactList.Labels.Where(l => l.Name == name).FirstOrDefault();
if( label != null )
label.Count += Convert.ToInt32(dr["LABEL_COUNT"]);
else
{
contactList.Labels.Add(
new Label()
{
Name = dr["LABEL_NAME"].ToString(),
Count = Convert.ToInt32(dr["LABEL_COUNT"])
}
);
}
I hope this code is readable and helpfulL!
}
This is other response:
Create and Object Model that can contain your required data:
public class DataResult
{
public ObservableCollection<AggregatedLabel> AggregatedLabels { get; set; }
public ObservableCollection<ContactList> ContactLists { get; set; }
}
You can build a method that return DataResult object, in your method (GetData()), you can valorize the two different properties (AggregatedLabels and ContactsList) with your DB Result. In the and you can return DataResult Object.
A little example here:
public DataResult GetData()
{
DataResult result = new DataResult();
result.AggregatedLabels = new ObservableCollection<AggregatedLabel>();
result.ContactLists = new ObservableCollection<ContactList>();
// Manipulate data result with your method logic like in this examle:
foreach(var something in dbResult)
{
ContactList cl = new ContactList() {
//Binding from something
}
result.ContactLists.Add(cl);
}
return result; //return your Object Model with required Data!
}
I hope it is conceptually clear

Categories