Generate list from treeitem using c# - asp.net-mvc-3

we have a list of the class
public class DummyClass
{
public string Text { get; set; }
public int LevelNo { get; set; }
public List<DummyClass> Children { get; set; }
}
we want to add this list to another list with class.
public class FragmentLevel
{
public int currentLevelNo { get; set; }
public int ParentLevelNo { get; set; }
public string Text { get; set; }
}
we need the result like
var list = new List<FragmentLevel>
{
new FragmentLevel{ id = 1, text = "Root" },
new FragmentLevel{ id = 2, parent= 1, text = "Node-1.1" },
new FragmentLevel{ id = 3, parent= 2, text = "Node-1.1.1" }
};
For getting result we are doing like
for (int i = 0; i < DummyClassList.Count; i++)
{
list.Add(new FragmentLevel
{
currentLevelNo = DummyClassList[i].LevelNo,
Text = DummyClassList[i].Text,
});
do
{
for (int j = 0; j < DummyClassList[i].Children.Count; j++)
{
list1.Add(new FragmentLevel
{
LevelNo = DummyClassList[i].Children[j].LevelNo,
Text = DummyClassList[i].Children[j].Text,
});
}
} while (DummyClassList[i].Children[i].Children != null);
}
But this will give wrong result. How we can get the result?

Try this way of filling the fragments recursively,
private static void FillFragments(List<DummyClass> DummyClassList, List<FragmentLevel> list)
{
for (int i = 0; i < DummyClassList.Count; i++)
{
list.Add(new FragmentLevel
{
currentLevelNo = DummyClassList[i].LevelNo,
Text = DummyClassList[i].Text,
});
if (DummyClassList[i].Children != null && DummyClassList[i].Children.Count > 0)
{
FillFragments(DummyClassList[i].Children, list);
}
}
}
and the main method would look like this
static void Main(string[] args)
{
var DummyClassList = new List<DummyClass>
{
new DummyClass
{
Children = new List<DummyClass>
{
new DummyClass{
Children = null,
LevelNo=2,
Text = "two"
}
},
LevelNo = 1,
Text = "one"
}
};
var list = new List<FragmentLevel>();
FillFragments(DummyClassList, list);
}

Related

How to bind Data Grid in DevExpress Xamarin

Generate headers like so:
public void ClearDataGrid()
{
this.xDataGrid.ItemsSource = null;
//// [Grid Headr 초기 세팅]
//this.xDataGrid.Columns.Clear();
//this.m_Model.MeasureData.Clear();
this.xDataGrid.Columns.Clear();
//// [Wave header 생성]
//Column cNo = GridUtil.Instance.SetColumn(ColumnTypes.Text, "No", "No", new ColumnWidth() { Value = 75 });
//this.xDataGrid.Columns.Add(cNo);
DevExpress.XamarinForms.DataGrid.TextColumn cNo = GridUtil.Instance.SetColumn(ColumnTypes.Text, "No", "No", 75) as DevExpress.XamarinForms.DataGrid.TextColumn;
this.xDataGrid.Columns.Add(cNo);
// [파장값 입력]
for (int i = 0; i < this.m_Model.WaveLength.Count; i++)
{
string strID = string.Empty;
if ((DisplayDataType)Enum.Parse(typeof(DisplayDataType), this.m_Model.DisplayDataUnitType.ToString()) == DisplayDataType.ABS)
{
strID = string.Format("ABS[{0}]", i);
DevExpress.XamarinForms.DataGrid.NumberColumn Col = GridUtil.Instance.SetColumn(
ColumnTypes.Numeric,
strID,
string.Format("A[{0}]", this.m_Model.WaveLength[i]),
150) as DevExpress.XamarinForms.DataGrid.NumberColumn;
this.xDataGrid.Columns.Add(Col);
}
else
{
strID = string.Format("Trans[{0}]", i);
DevExpress.XamarinForms.DataGrid.NumberColumn Col = GridUtil.Instance.SetColumn(
ColumnTypes.Numeric,
strID,
string.Format("T[{0}]", this.m_Model.WaveLength[i]),
150) as DevExpress.XamarinForms.DataGrid.NumberColumn;
this.xDataGrid.Columns.Add(Col);
}
}
DevExpress.XamarinForms.DataGrid.TextColumn cCell = GridUtil.Instance.SetColumn(ColumnTypes.Text, "Cell", "Cell", 75) as DevExpress.XamarinForms.DataGrid.TextColumn;
DevExpress.XamarinForms.DataGrid.DateColumn cDateTime
= GridUtil.Instance.SetColumn(ColumnTypes.Date, "Date", "Date", 150) as DevExpress.XamarinForms.DataGrid.DateColumn;
this.xDataGrid.Columns.Add(cCell);
this.xDataGrid.Columns.Add(cDateTime);
this.xDataGrid.ItemsSource = this.m_Model.MeasureData;
}
When a button is clicked, temporary data is created and added to the bound model.
private async void BtnMeasureClick(object sender, EventArgs e)
{
PhotometricMeasureData data = new PhotometricMeasureData();
++nIndex;
data.No = nIndex.ToString();
data.Cell = string.Format("C[{0}]", nIndex);
data.DateTime = DateTime.Now;
for (int i = 0; i < this.m_Model.WaveLength.Count; i++)
{
data.OriginABS.Add(new Random().Next(-10, 10));
data.OriginTrans.Add(new Random().Next(-10, 10));
data.ABS.Add(data.OriginABS[i] * this.m_Model.Factor);
data.Trans.Add(data.OriginTrans[i] * this.m_Model.Factor);
}
this.m_Model.MeasureData.Add(data);
//this.xDataGrid.Columns[0].Pinned = PinnedPositions.Left;
//this.xDataGrid.ScrollToLastRowByIndex(this.m_Model.MeasureData.Count-1);
}
binding model
public BindingList<PhotometricMeasureData> MeasureData
{
set; get;
} = new BindingList<PhotometricMeasureData>();
public class PhotometricMeasureData : INotifyPropertyChanged
{
//List<float> m_lstABS = new List<float>();
//List<float> m_lstTrans = new List<float>();
public string No { get; set; }
public string Cell { get; set; }
public DateTime DateTime { get; set; }
public BindingList<float> ABS
{
get; set;
} = new BindingList<float>();
public BindingList<float> Trans
{
get; set;
} = new BindingList<float>();
public BindingList<float> OriginABS
{
get; set;
} = new BindingList<float>();
public BindingList<float> OriginTrans
{
get; set;
} = new BindingList<float>();
public void UpdateABSByFactor(float factor)
{
//this.ABS.Clear();
for (int i = 0; i < this.ABS.Count; i++)
{
this.ABS[i] = this.OriginABS[i] * factor;
OnPropertyChanged(string.Format("ABS[{0}]", i));
}
}
public void UpdateTransByFactor(float factor)
{
//this.Trans.Clear();
for (int i = 0; i < this.Trans.Count; i++)
{
this.Trans[i] = this.OriginTrans[i] * factor;
OnPropertyChanged(string.Format("Trans[{0}]", i));
}
}
public event PropertyChangedEventHandler PropertyChanged;
void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
In the current bound model, No and Cell DateTime are binding fine.
But the data created by BindingList is not being bound.
When creating a column in the header, the field name was created and inserted like string.Format("ABS[{0}]", i).
And I tried to bind the data accessed by the index of the ABS list of the binding model.
But it doesn't work as well as I thought.
What am I doing wrong?
enter image description here
enter image description here

For Loop Returning A Range

my BlueJ project has 2 classes: StateProvince and Country. Below is the StateProvince class first, then the Country class where I'm at. I'm stuck on a method: "public int howManyHaveThisPopulation(int min, int max)" which takes the population in millions(e.g. 4, 6) and returns how many StateProvinces there are with populations in that range(e.g. 4-6 million, inclusive). I am not able to set it up and return the right answer. I would like help on how I can do this please. With how my method is now, the error message is that I'm missing a return statement. I know my method isn't correct. I have listed the class below and my progress on the method:
public class StateProvince
{
private String name; //e.g. "British Columbia" or "California"
private String capital; //e.g. "Victoria or "Sacramento"
private int populationInMillions; //e.g. 4 or 38
private final static int DEFAULT_POPULATION_MILLIONS = 4;
private final static String DEFAULT_STATE_PROVINCE = "British Columbia";
private final static String DEFAULT_CAPITAL = "Victoria";
public StateProvince()
{
}
/**
* constructor that takes in all 3 parameters and assigns them if they follow the rules:
* name: must be one of the 50 Unites States or 10 Canadian Provinces
* capital: must be the name of the capital city
* populationInMillions: must be between 0 and 38
*/
public StateProvince(String name, String capital, int populationInMillions)
{
if(isValidPopulation(populationInMillions) && (isValidStateProvince(name) &&
(isValidCapitalCity(capital))))
{
this.populationInMillions = populationInMillions;
this.name = name;
this.capital = capital;
}else
{
this.populationInMillions = DEFAULT_POPULATION_MILLIONS; //
this.name = DEFAULT_STATE_PROVINCE; //"British Columbia"
this.capital = DEFAULT_CAPITAL; //"Victoria"
}
}
//StateProvince p1 = new StateProvince("British Columbia", "Victoria", 5);
private boolean isValidStateProvince(String name)
{
String[] provinces = new String[10];
provinces[0] = "British Columbia";
provinces[1] = "Alberta";
provinces[2] = "Saskatchewan";
provinces[3] = "Manitoba";
provinces[4] = "Ontario";
provinces[5] = "Quebec";
provinces[6] = "PEI";
provinces[7] = "Newfoundland";
provinces[8] = "New Brunswick";
provinces[9] = "Nova Scotia";
for(int index = 0; index < provinces.length; index++)
{
if(provinces[index].equalsIgnoreCase(name))
{
return true;
}
index++;
}
return false;
}
private boolean isValidCapitalCity(String capital)
{
String[] capitals = new String[10];
capitals[0] = "Victoria";
capitals[1] = "Edmonton";
capitals[2] = "Regina";
capitals[3] = "Winnipeg";
capitals[4] = "Toronto";
capitals[5] = "Quebec City";
capitals[6] = "Charlottetown";
capitals[7] = "St. John's";
capitals[8] = "Fredericton";
capitals[9] = "Halifax";
for(int index = 0; index < capitals.length; index++)
{
if(capitals[index].equalsIgnoreCase(capital))
{
return true;
}
index++;
}
return false;
}
private boolean isValidPopulation(int populationInMillions)
{
if(populationInMillions >= 4 || populationInMillions <= 38)
{
return true;
}else
{
return false;
}
}
public void setName()
{
this.name = name;
}
public void setCapital()
{
this.capital = capital;
}
public String getName()
{
return name;
}
public String getCapital()
{
return capital;
}
public int getPopulationInMillions()
{
return populationInMillions;
}
public String getDetails()
{
return ("The capital of " + getName() + " (pop. " + populationInMillions + " million) is " + getCapital());
}
}
public class Country
{
private String country;
private StateProvince[] Canada;
public Country()
{
Canada = new StateProvince[10];
Canada[0] = new StateProvince("British Columbia", "Victoria", 4);
Canada[1] = new StateProvince("Alberta", "Edmonton", 3);
Canada[2] = new StateProvince("Saskatchewan", "Regina", 1);
Canada[3] = new StateProvince("Manitoba", "Winnipeg", 1);
Canada[4] = new StateProvince("Ontario", "Toronto", 13);
Canada[5] = new StateProvince("Quebec", "Quebec City", 8);
Canada[6] = new StateProvince("PEI", "Charlottetown", 0);
Canada[7] = new StateProvince("Newfoundland", "St. John's", 0);
Canada[8] = new StateProvince("New Brunswick", "Fredericton", 1);
Canada[9] = new StateProvince("Nova Scotia", "Halifax", 1);
}
public void displayAllStates()
{
for(int index = 0; index < Canada.length; index++)
{
if(Canada[0] != null)
{
System.out.println(Canada[index].getDetails());
}
index++;
}
}
public void addStateProvince(StateProvince stateProvince)
{
if(Canada != null)
{
for(int i = 0; i < Canada.length; i++)
{
if(Canada[i] == null)
{
Canada[i] = stateProvince;
return;
}
}
}
}
public int howManyHaveThisPopulation(int min, int max)
{
for(int i = 0; i < Canada.length; i++)
{
if(i > min && i < max)
{
return Canada[i].getPopulationInMillions();
}
}
}

How to apply exact instead match by Nest api?

How can I get AEntity where BEntityProp equals "Bprop 3"?
internal class Program
{
public class AEntity
{
public Guid Id { get; set; }
public BEntity BEntityProp { get; set; }
}
public class BEntity
{
public Guid Id { get; set; }
public string Bprop { get; set; }
}
private static void Main(string[] args)
{
var node = new Uri("http://localhost:9200");
var settings = new ConnectionSettings(node, defaultIndex: "default_index");
var client = new ElasticClient(settings);
var entities = new List<AEntity>(100);
for (var i = 0; i < 100; i++)
client.Index(new AEntity
{
Id = Guid.NewGuid(),
BEntityProp =
new BEntity
{
Id = Guid.NewGuid(),
Bprop = "Bprop " + i.ToString(CultureInfo.InvariantCulture)
}
});
Thread.Sleep(1000);
var searchDescriptor = new SearchDescriptor<AEntity>();
//how to apply exact instead match by Nest api?
List<AEntity> expected = client.Search<AEntity>(
searchDescriptor.Query(qd => qd.Match(
mqd => mqd.OnField(x => x.BEntityProp.Bprop).Query("bprop 3")))).Documents.ToList();
try
{
Assert.IsTrue(expected.Count == 1);
}
finally
{
client.DeleteIndex(di => di.Indices("default_index", "default_index" + "*"));
}
}
}
As a result I want to have 1 AEntity with Bprop equals "Bprop 3" but I have all matches "Bprop".
The request looks like:
expected :
{
"query": {
"match": { <-- how to apply exact instead match by Nest api?
"bEntityProp.bprop": {
"query": "bprop 3"
}
}
}
}
I found the ansvwer :
List<AEntity> expected = client.Search<AEntity>(
searchDescriptor.Query(qd => qd.MatchPhrase(
mqd => mqd.OnField(x => x.BEntityProp.Bprop).Query("bprop 3")))).Documents.ToList();
If you want the exact match then use a Term query:
List<AEntity> expected = client.Search<AEntity>(
searchDescriptor.Query(qd => qd.Term(
mqd => mqd.OnField(x => x.BEntityProp.Bprop).Value("bprop 3"))))
.Documents.ToList();
More on Term vs Match can be found in this discussion.

ProtoBuf-Linq error message “ Invalid field in source data: 0”

I've encountered the following issue while using protobuf-linq:
using (var stream = new MemoryStream())
{
SerializeMultiple(PrepareData(), stream);
}
private static void SerializeMultiple(IEnumerable<Person> persons, Stream stream)
{
foreach (var person in persons)
{
Serializer.Serialize(stream, person);
}
stream.Position = 0;
var q = RuntimeTypeModel.Default.AsQueryable<Person>(stream,null);
var results = from e in q
where e.Id % 2 == 0
select new { e.Id, e.Name };
Console.WriteLine("first : " + results.First().Id);
Console.ReadLine();
}
static IEnumerable<Person> PrepareData()
{
for (int i = 0; i < (int) 1e+04; i++)
{
yield return new Person {Id = i, Name= "John" + i, Address = "Address" + i*i};
}
}
[ProtoContract]
class Person
{
[ProtoMember(1)]
public int Id { get; set; }
[ProtoMember(2)]
public string Name { get; set; }
[ProtoMember(3)]
public string Address { get; set; }
}
The AsQueryable line throws the aforementioned exception:
Invalid field in source data: 0
Any thoughts on this matter?
It's not protobuf-linq error. When serializing items into a stream, you should use SerializeWithLengthPrefix to prefix every message with its length, to allow separate them. By default, protobuf-linq uses PrefixStyle.Base128. Below you can find a snippet making it right:
Serializer.SerializeWithLengthPrefix(stream, person, PrefixStyle.Base128);

Help with linq query. many to many

I have a collection(people) that has a many-to-many reference to another collection(dogs). Suspend your disbelief on how there can be more than one people per dog. People just contains member which is an List<Dog>
I would like to select all the people where the people have a certain property(specified in an IList) and pets have a certain property(specified in an IList).
E.g. I have an IList (used for this query only) with the dog’s property value.
public enum EnumLikesToBite
{
No,
Yes,
Sometimes
}
IList <<EnumLikesToBite>> listDogsMayBite =
{ { EnumLikesToBite.Yes},
{ EnumLikesToBite.Sometimes}};
Then another list for the peoples property:
public enum EnumKeepsPetWith
{
Chain,
String,
Rubberband
}
IList <EnumKeepsPetWith> listPeopleWhoDontRestrainDog =
{ { EnumKeepsPetWith.String },
{ EnumKeepsPetWith.Rubberband}};
How can I query out all the people who have a dog that may bite and don’t restrain dog.
Like this pseudo code:
Var result = from p in People where p.KeepsPet in listPeopleWhoDontRestrainDog and dog.LikesToBite in listDogsMayBite.
Result has all the people. Of course if I could get all the dogs who may bite under those people that would be great.
List<int> mayBite = new List<int>()
{
(int) EnumLikesToBite.Yes,
(int) EnumLikesToBite.Maybe
}
List<int> poorRestraint = new List<int>()
{
(int) EnumKeepsPetWith.String,
(int) EnumKeepsPetWith.RubberBand
}
IQueryable<Person> query =
from p in db.People
where poorRestraint.Contains(p.KeepsPetWith)
where p.DogPeople.Any(dp => mayBite.Contains(dp.Dog.DoesBite))
select p;
var query =
from p in db.People
where poorRestraint.Contains(p.KeepsPetWith)
let bitingDogs =
from dp in p.DogPeople
let d = dp.Dog
where mayBite.Contains(d.DoesBite)
where bitingDogs.Any()
select new {Person = p, BitingDogs = bitingDogs.ToList()};
Maybe this code will help.. One of the possible solution are:
var result =
peoples.Where(y => dontRestrainDog.Contains(y.KeepsPetWith) && y.Dogs.Any(x => dogsMayBite.Contains(x.LikesToBite))).ToList();
result.ForEach(y => y.Dogs = y.Dogs.Where(x => dogsMayBite.Contains(x.LikesToBite)).ToList());
which you can see an example of here:
class Program
{
static void Main(string[] args)
{
IList<EnumLikesToBite> dogsMayBite = new List<EnumLikesToBite>
{
{ EnumLikesToBite.Yes }, { EnumLikesToBite.Sometimes }
};
IList<EnumKeepsPetWith> dontRestrainDog = new List<EnumKeepsPetWith>
{
{ EnumKeepsPetWith.String }, { EnumKeepsPetWith.Rubberband }
};
var peoples = new List<People>();
var dogs = new List<Dog>();
Random gen = new Random(2);
for(int i = 0; i < 10; i++)
{
People p = new People
{
PeopleId = i,
KeepsPetWith = (EnumKeepsPetWith) (gen.Next(10)%3),
Dogs = new List<Dog>()
};
Dog d = new Dog
{
DogId = i,
LikesToBite = (EnumLikesToBite) (gen.Next(10)%3),
Peoples = new List<People>()
};
peoples.Add(p);
dogs.Add(d);
}
for(int i = 0; i < 10; i++)
{
for(int j = 0; j < 10; j++)
{
if (gen.Next(10)>7)
{
peoples[i].Dogs.Add(dogs[j]);
}
if (gen.Next(10)>7)
{
dogs[i].Peoples.Add(peoples[j]);
}
}
}
PrintDogs(dogs);
PrintPeoples(peoples);
var result =
peoples.Where(y => dontRestrainDog.Contains(y.KeepsPetWith) && y.Dogs.Any(x => dogsMayBite.Contains(x.LikesToBite))).ToList();
result.ForEach(y => y.Dogs = y.Dogs.Where(x => dogsMayBite.Contains(x.LikesToBite)).ToList());
Console.WriteLine("===================");
PrintPeoples(result);
Console.ReadLine();
}
private static void PrintPeoples(List<People> peoples)
{
Console.WriteLine("=Peoples=");
foreach (var people in peoples)
{
Console.WriteLine("Id: {0}", people.PeopleId);
Console.WriteLine("KeepsPetWith: {0}", people.KeepsPetWith);
Console.WriteLine("Dogs: ");
foreach (var dog in people.Dogs)
{
Console.Write("{0}, ", dog.DogId);
}
Console.WriteLine();
}
}
private static void PrintDogs(List<Dog> dogs)
{
Console.WriteLine("=Dogs=");
foreach (var dog in dogs)
{
Console.WriteLine("Id: {0}", dog.DogId);
Console.WriteLine("LikesToBite: {0}", dog.LikesToBite);
Console.WriteLine("Peoples: ");
foreach (var people in dog.Peoples)
{
Console.Write("{0}, ", people.PeopleId);
}
Console.WriteLine();
}
}
}
public class People
{
public int PeopleId { get; set; }
public EnumKeepsPetWith KeepsPetWith { get; set; }
public IList<Dog> Dogs { get; set; }
}
public class Dog
{
public int DogId { get; set; }
public EnumLikesToBite LikesToBite { get; set; }
public IList<People> Peoples { get; set; }
}
public enum EnumLikesToBite
{
No,
Yes,
Sometimes
}
public enum EnumKeepsPetWith
{
Chain,
String,
Rubberband
}

Resources