I've a collection of DataItem class.
DataItem : Property RefItem stores ref to a DataItem that could be same collection.
public class DataItem
{
public int ID { get; set; }
public string Name { get; set; }
public DataItem RefItem { get; set; }
}
Collection:
private List<DataItem> dataitems;
public List<DataItem> DataItems
{
get { return dataitems; }
set { dataitems = value; }
}
Now I have two methods for adding data in the collection and validating data in collection.
public void AddItem(DataItem item)
{
DataItems.Add(item);
}
public bool ValidateDataItems()
{
//Logic for circular reference
//
return true;
}
I want a algorithm in validate method to check if there is any circular dependency in my collection.For ex. Below is an invalid data for me. As item3 is again pointed by item1.
var item1 = new DataItem() {ID=1,Name="First Item",RefItem =null};
var item2 = new DataItem() { ID = 1, Name = "First Item", RefItem = item1 };
var item3 = new DataItem() { ID = 1, Name = "First Item", RefItem = item2 };
item1.RefItem = item3;
AddItem(item1);
AddItem(item2);
AddItem(item3);
If items are added to collection like Item1->item2,item2-> item3,item3->item1 or any other possible combination of where a ref item of a class is pointing back. I want validation method to return false.
It's a circular dependency problem but I couldn't find any concrete algorithm to do so in c#.