I need to add a ObservableCollection ObservableCollection within another, is it possible?
Items = new ObservableCollection<WidgetCollectionItem>();
foreach (XElement wid in document.Root.Elements("widget"))
{
WidgetCollectionItem item = new WidgetCollectionItem();
item.nombreWidget = wid.Attribute("caption").Value;
foreach (XElement service in wid.Elements("service"))
{
item.nombreServicio = service.Attribute("caption").Value;
item.valor = service.Element("xvalue").Value;
item.color = service.Element("xcolor").Value;
item.alerta = service.Element("xalert") != null ? service.Element("xalert").Value : null;
Items.Add(item);
}
}
The problem is that each (item.nombreWidget) contains more than one (item.nombreServicio). And I need a ObservableCollection of services within an ObservableCollection of nombreWidget
Yes, you can.
new ObservableCollection<ObservableCollection<WidgetCollectionItem>>()
so you can do something like this:
Items = new ObservableCollection<ObservableCollection<WidgetCollectionItem>>();
foreach (XElement wid in document.Root.Elements("widget"))
{
ObservableCollection<WidgetCollectionItem> services = new ObservableCollection<WidgetCollectionItem>();
foreach (XElement service in wid.Elements("service"))
{
WidgetCollectionItem widget = new WidgetCollectionItem();
widget.nombreWidget = wid.Attribute("caption").Value;
widget.nombreServicio = service.Attribute("caption").Value;
widget.valor = service.Element("xvalue").Value;
widget.color = service.Element("xcolor").Value;
widget.alerta = service.Element("xalert") != null ? service.Element("xalert").Value : null;
services.Add(widget);
}
Items.Add(services)
}
Good idea kindasimple, but still can not show what I want. I grab a xml data, and these want them displayed in a grid
The end result would be this:
nombreWidget1
nombreServicio1
nombreWidget2
nombreServicio2
nombreServicio2
nombreServicio2
If nombreWidget has only one service is fine, but if you have more than one nombreWidget nombreServicio, I can not show well on screen
I need the ObservableCollection
public class WidgetCollectionItem
{
public string nombreWidget { get; set; }
}
Contains an ObservableCollection
public class WidgetServiciosCollectionItem
{
public string nombreServicio { get; set; }
public string valor { get; set; }
public string color { get; set; }
public string alerta { get; set; }
}
Looks like I got what I wanted to achieve, but still does not show me all the data in the grid:
Solution to earlier:
Items = new ObservableCollection<WidgetCollectionItem>();
foreach (XElement wid in document.Root.Elements("widget"))
{
WidgetCollectionItem widget = new WidgetCollectionItem();
widget.nombreWidget = wid.Attribute("caption").Value;
foreach (XElement service in wid.Elements("service"))
{
ServiciosWidgetCollectionItem ser = new ServiciosWidgetCollectionItem();
widget.ItemsSer = new ObservableCollection<ServiciosWidgetCollectionItem>();
ser.nombreServicio = service.Attribute("caption").Value;
ser.valor = service.Element("xvalue").Value;
ser.color = service.Element("xcolor").Value;
ser.alerta = service.Element("xalert") != null ? service.Element("xalert").Value : null;
widget.ItemsSer.Add(ser);
}
Items.Add(widget);
}
public class WidgetCollectionItem
{
public string nombreWidget { get; set; }
public ObservableCollection<ServiciosWidgetCollectionItem> ItemsSer { get; set; }
}
public class ServiciosWidgetCollectionItem
{
public string nombreServicio { get; set; }
public string valor { get; set; }
public string color { get; set; }
public string alerta { get; set; }
}
How do I go also in the data grid ObservableCollection?
Related
Here is the GET REQUEST
var destname = textBox1.Text;
var client1 = new RestClient("https://skyscanner-skyscanner-flight-search-v1.p.rapidapi.com/apiservices/autosuggest/v1.0/UK/GBP/en-GB/?query=" + destname);
var request1 = new RestRequest(Method.GET);
request1.AddHeader("x-rapidapi-key", "");
request1.AddHeader("x-rapidapi-host", "skyscanner-skyscanner-flight-search-v1.p.rapidapi.com");
IRestResponse response1 = client1.Execute(request1);
var results = JsonConvert.DeserializeObject<DestinationName>(response1.Content);
And here is the classes
public partial class Place1
{
public string PlaceId { get; set; }
public string PlaceName { get; set; }
public string CountryId { get; set; }
public string RegionId { get; set; }
public string CityId { get; set; }
public string CountryName { get; set; }
}
public partial class DestinationName
{
public List<Place1> Places { get; set; }
}
When I do what is below I should be getting ES-sky which is the first element of the list but for some reason it gives me the last element of the list.
foreach (var a in results.Places)
{
label1.Text = a.PlaceId;
}
Here is the list
ES-sky
BCN-sky
ALC-sky
AGP-sky
MAD-sky
PMI-sky
IBZ-sky
TENE-sky
TFS-sky
TFN-sky
How would I adapt the code so that my output is ES-sky and not TFN-sky.
You are looping through the list, every time its writing value to "label1.Text". Use SingleOrDefault()/FirstOrDefault(). Dont use foreach loop.
Example:
var firstValue=results.Places.FirstOrDefault();
label1.Text = firstValue.PlaceId;
Instead of iterating through the loop here:
foreach (var a in results.Places)
{
label1.Text = a.PlaceId;
}
Just get the first value with appropriate validation:
if(results.Places != null && results.Places.Any())
{
var result = results.Places.First();
label1.Text = a.PlaceId;
}
You can bind only first place data in list from server side and get it on client side OR
bind FirstorDefault method to get first place data from list in client side.
I have a C# project and looking for simple solution for map one class object data to list of another class object.
This is my input class
public class RatesInput
{
public string Type1 { get; set; }
public string Break1 { get; set; }
public string Basic1 { get; set; }
public string Rate1 { get; set; }
public string Type2 { get; set; }
public string Break2 { get; set; }
public string Basic2 { get; set; }
public string Rate2 { get; set; }
public string Type3 { get; set; }
public string Break3 { get; set; }
public string Basic3 { get; set; }
public string Rate3 { get; set; }
}
This is my another class structure
public class RateDetail
{
public string RateType { get; set; }
public decimal Break { get; set; }
public decimal Basic { get; set; }
public decimal Rate { get; set; }
}
it has a object like below. (For easiering the understanding, I use hardcoded values and actually values assign from a csv file)
RatesInput objInput = new RatesInput();
objInput.Type1 = "T";
objInput.Break1 = 100;
objInput.Basic1 = 50;
objInput.Rate1 = 0.08;
objInput.Type2 = "T";
objInput.Break2 = 200;
objInput.Basic2 = 50;
objInput.Rate2 = 0.07;
objInput.Type3 = "T";
objInput.Break3 = 500;
objInput.Basic3 = 50;
objInput.Rate3 = 0.06;
Then I need to assign values to "RateDetail" list object like below.
List<RateDetail> lstDetails = new List<RateDetail>();
//START Looping using foreach or any looping mechanism
RateDetail obj = new RateDetail();
obj.RateType = //first iteration this should be assigned objInput.Type1, 2nd iteration objInput.Type2 etc....
obj.Break = //first iteration this should be assigned objInput.Break1 , 2nd iteration objInput.Break2 etc....
obj.Basic = //first iteration this should be assigned objInput.Basic1 , 2nd iteration objInput.Basic2 etc....
obj.Rate = //first iteration this should be assigned objInput.Rate1, 2nd iteration objInput.Rate2 etc....
lstDetails.Add(obj); //Add obj to the list
//END looping
Is there any way to convert "RatesInput" class data to "RateDetail" class like above method in C#? If yes, how to iterate data set?
Try this:
public class RatesList : IEnumerable<RateDetail>
{
public RatesList(IEnumerable<RatesInput> ratesInputList)
{
RatesInputList = ratesInputList;
}
private readonly IEnumerable<RatesInput> RatesInputList;
public IEnumerator<RateDetail> GetEnumerator()
{
foreach (var ratesInput in RatesInputList)
{
yield return new RateDetail
{
RateType = ratesInput.Type1,
Break = Convert.ToDecimal(ratesInput.Break1, new CultureInfo("en-US")),
Basic = Convert.ToDecimal(ratesInput.Basic1, new CultureInfo("en-US")),
Rate = Convert.ToDecimal(ratesInput.Rate1, new CultureInfo("en-US"))
};
yield return new RateDetail
{
RateType = ratesInput.Type2,
Break = Convert.ToDecimal(ratesInput.Break2),
Basic = Convert.ToDecimal(ratesInput.Basic2),
Rate = Convert.ToDecimal(ratesInput.Rate2, new CultureInfo("en-US"))
};
yield return new RateDetail
{
RateType = ratesInput.Type3,
Break = Convert.ToDecimal(ratesInput.Break3),
Basic = Convert.ToDecimal(ratesInput.Basic3),
Rate = Convert.ToDecimal(ratesInput.Rate3, new CultureInfo("en-US"))
};
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
And use:
var list = new RatesList(new List<RatesInput>() { objInput });
foreach (var item in list)
{
Console.WriteLine(item.Basic);
}
You can use Reflection to get the properties info like this:
var props = objInput.GetType().GetProperties();
var types = props.Where(x => x.Name.StartsWith("Type"))
.Select(x => x.GetValue(objInput)).ToList();
var breaks = props.Where(x => x.Name.StartsWith("Break"))
.Select(x => x.GetValue(objInput)).ToList();
var basics = props.Where(x => x.Name.StartsWith("Basic"))
.Select(x => x.GetValue(objInput)).ToList();
var rates = props.Where(x => x.Name.StartsWith("Rate"))
.Select(x => x.GetValue(objInput)).ToList();
List<RateDetail> lstDetails = new List<RateDetail>();
for (int i = 0; i < types.Count; i++)
{
lstDetails.Add(new RateDetail
{
RateType = types[i].ToString(),
Break = Convert.ToDecimal(breaks[i]),
Basic = Convert.ToDecimal(basics[i]),
Rate = Convert.ToDecimal(rates[i])
});
}
I need to populate a dropdown in my UI and hence added List object to the view model in my c# application. I am fetching the data in my controller code for the dropdown. What's the best way to assign data to the viewmodel object. Is linq an option?
I basically need to assign fundclasses to fundTrackRecord.FundClass
The main Viewmodel:
public class FundPerformanceVM
{
public FundPerformanceVM()
{
TrackRecord = new List<TrackRecordVM>();
}
public int FundId { get; set; }
public string FundName { get; set; }
public List<FundClassVM> FundClass { get; set; }
public string BenchmarkName1 { get; set; }
public string BenchmarkName2 { get; set; }
public List<TrackRecordVM> TrackRecord { get; set; }
public List<Tuple<string, string, string>> FundStatistics { get; set; }
}
public class FundClassVM
{
public int FundClassId { get; set; }
public string FundClass { get; set; }
}
Controller code:
var service = GetViewService<V_LEGAL_FUND_CLASS_SUMMARY>();
foreach (KeyValuePair<int, IEnumerable<FUND_PERFORMANCE>> entry in allPerformance)
{
var fundClasses = service.GetAll().Where(x => x.FUND_ID == entry.Key).Select(x => new { x.LEGAL_FUND_CLASS_ID, x.LEGAL_FUND_CLASS}).ToList();
var fundTrackRecord = new FundPerformanceVM();
fundTrackRecord.FundClass = ??;
If I understood correctly the structure of your model, you can try this:
fundTrackRecord.FundClass = fundClasses.Select(fc => new FundClassVM
{
FundClassId = fc.LEGAL_FUND_CLASS_ID,
FundClass = fc.LEGAL_FUND_CLASS
}).ToList();
You can also do this directly, replacing the code:
var fundClasses = service.GetAll().Where(x => x.FUND_ID == entry.Key).Select(x => new { x.LEGAL_FUND_CLASS_ID, x.LEGAL_FUND_CLASS}).ToList();
var fundTrackRecord = new FundPerformanceVM();
With:
var fundTrackRecord = new FundPerformanceVM();
fundTrackRecord.FundClass = service.GetAll().
Where(x => x.FUND_ID == entry.Key).
Select(fc => new FundClassVM
{
FundClassId = fc.LEGAL_FUND_CLASS_ID,
FundClass = fc.LEGAL_FUND_CLASS
}).ToList();
public class kingdomAddModel
{
public string title { get; set; }
public string details { get; set; }
//public HttpPostedFileBase fileUpload { get; set; }
//public string retrieveFile { get; set; }
public FileAttr files { get; set; }
}
public class FileAttr
{
public HttpPostedFileBase fileUpload { get; set; }
public string retrieveFile { get; set; }
}
var getDailyDevotions = db.DailyDevotions.Select(d => new { title = d.DevotionsTitle, details = d.DevotionsDetails, retriveFileAudio = d.VoiceNotes });
List<kingdomAddModel> listdevotions = new List<kingdomAddModel>();
foreach (var getDevotions in getDailyDevotions)
{
kingdomlist = new kingdomAddModel();
kingdomlist.title = getDevotions.title;
kingdomlist.details = getDevotions.details;
fileattr = new FileAttr();
fileattr.retrieveFile = getDevotions.retriveFileAudio;
kingdomlist.files.retrieveFile = fileattr.retrieveFile; //erros appears here!
}
The line line kingdomlist.files.retrieveFile throws the exception, tried googling but I dont get simular problem. I just want to assign the value and will pull on my view.
Do not access properties of FileAttr directly, only use files with the instance of kingdomAddModel. Don't mixup them
Replace
foreach (var getDevotions in getDailyDevotions)
{
kingdomlist = new kingdomAddModel();
kingdomlist.title = getDevotions.title;
kingdomlist.details = getDevotions.details;
fileattr = new FileAttr();
fileattr.retrieveFile = getDevotions.retriveFileAudio;
kingdomlist.files.retrieveFile = fileattr.retrieveFile; //erros appears here!
}
with
foreach (var getDevotions in getDailyDevotions)
{
kingdomlist = new kingdomAddModel
{
title = getDevotions.title,
details = getDevotions.details,
files = new FileAttr
{
retrieveFile = getDevotions.retriveFileAudio,
//fileUpload = some value here
}
};
listdevotions.Add(kingdomlist);
}
OR use Linq
listdevotions = (from getDevotions in getDailyDevotions
select new kingdomAddModel
{
title = getDevotions.title,
details = getDevotions.details,
files = new FileAttr
{
retrieveFile = getDevotions.retriveFileAudio,
//fileUpload = some value here
}
}).ToList();
Im trying to use Linq to select the property ProductColor from a List of MyObject into the property AllProductColors
public class MyObject
{
public string ImgUrl { get; set; }
public string ProductName { get; set; }
public string ProductColor { get; set; }
}
public class ObjectToSelectInto
{
public string ImgUrl { get; set; }
public string ProductName { get; set; }
public List<string> AllProductColors { get; set; }
}
//*** CREATING EXAMPLE ***///
List<MyObject> MyObjectList = new List<MyObject>();
ObjectToSelectInto destinationObject = new ObjectToSelectInto();
//I can do it like this, but then I
// would have to do this for every list item, not good!
destinationObject.AllProductColors =
MyObjectList.Select(x => x.ProductColor).toList();
//*** This fails ***///
destinationObject = MyObjectList.Select( x =>
new destinationObject {
AllProductColors = x.ProductColor.ToList(),
ImgUrl = x.ImgUrl.First().toString(),
ProductName = x.ProductName .First().toString()
}
I want it to be like this.
destinationObject has a list with elements where one color equals one element.
You just need to put your first query that you tried into second like this:
destinationObject = MyObjectList.Select(x =>
new ObjectToSelectInto()
{
AllProductColors = MyObjectList.Select(y => y.ProductName).ToList(),
ImgUrl = x.ImgUrl,
ProductName = x.ProductName
}).First();