I am trying to flat this data into a viewmodel but I am not sure how to do it. The example below is the type of data I am working with. It has a list of object with another list of objects and it should flatted the ListOfCarModel and build the viewmodel. Any help would be great.
static void Main(string[] args)
{
try
{
List<carmake> carmakes = new List<carmake>();
List<carmodel> carmodel = new List<carmodel>();
carmodel.Add(new carmodel() { Modelid = 1, Model = "S60" });
carmodel.Add(new carmodel() { Modelid = 2, Model = "A4" });
carmodel.Add(new carmodel() { Modelid = 3, Model = "A4s" });
carmakes.Add(new carmake() { Makeid = 1, MakeName = "Volvo",ListOfCarModel= carmodel });
List<carmodel> carmodel2 = new List<carmodel>();
carmodel2.Add(new carmodel() { Modelid = 4, Model = "535d" });
carmodel2.Add(new carmodel() { Modelid = 5, Model = "320d" });
carmodel2.Add(new carmodel() { Modelid = 6, Model = "M5" });
carmakes.Add(new carmake() { Makeid = 2, MakeName = "BMW",ListOfCarModel= carmodel2 });
List<carmodel> carmodel3 = new List<carmodel>();
carmodel2.Add(new carmodel() { Modelid = 4, Model = "Passat" });
carmodel2.Add(new carmodel() { Modelid = 5, Model = "dd" });
carmodel2.Add(new carmodel() { Modelid = 6, Model = "aaa" });
carmakes.Add(new carmake() { Makeid = 3, MakeName = "VW", ListOfCarModel = carmodel3 });
var listOfCars = carmakes.Select(x => new CarViewModel
{
Model = x.MakeName,
//MakeName = x.ListOfCarModel.SelectMany(x.ListOfCarModel)
});.ToList()
}
catch (Exception ex)
{
ex.ToString();
}
}
class carmake
{
public int Makeid { get; set; }
public string MakeName { get; set; }
public List<carmodel> ListOfCarModel { get; set; }
}
class carmodel
{
public int Modelid { get; set; }
public string Model { get; set; }
}
class CarViewModel
{
public string MakeName { get; set; }
public string Model { get; set; }
}
}
Try this:
List<CarViewModel> viewModels = new List<CarViewModel>();
foreach (var make in carmakes)
foreach (var model in make.ListOfCarModel)
viewModels.Add(new CarViewModel() { MakeName = make.MakeName, Model = model.Model });
Or if you want to use LINQ:
List<CarViewModel> viewModels = carmakes
.Select(carmake => carmake.ListOfCarModel.Select(x => new CarViewModel() { MakeName = carmake.MakeName, Model = x.Model }))
.SelectMany(x => x)
.ToList();
Related
I need a function that converts categories into flats (see code bellow).
I get categories from the database and then I want to convert them into a breadcrumbs format so I can later display them in a combobox.
using System.Collections.Generic;
namespace ConsoleApp4
{
class Program
{
static void Main(string[] args)
{
var categories = new List<ProductCategory>
{
new ProductCategory { ProductCategoryId = 1, ParentId = null, Name = "Drinks" },
new ProductCategory { ProductCategoryId = 2, ParentId = null, Name = "Food" },
new ProductCategory { ProductCategoryId = 3, ParentId = 1, Name = "Beers" },
new ProductCategory { ProductCategoryId = 4, ParentId = 1, Name = "Wines" },
new ProductCategory { ProductCategoryId = 5, ParentId = 3, Name = "Local beers" },
new ProductCategory { ProductCategoryId = 6, ParentId = 3, Name = "Foreign beers" },
new ProductCategory { ProductCategoryId = 7, ParentId = 4, Name = "Red wines" },
new ProductCategory { ProductCategoryId = 8, ParentId = 4, Name = "White wines" },
};
// todo to get below structure...
var flats = new List<ProductCategoryFlatItem>
{
new ProductCategoryFlatItem { NameWithAncestors = "Drinks", ProductCategoryId = 1 },
new ProductCategoryFlatItem { NameWithAncestors = "Drinks / Beers", ProductCategoryId = 3 },
new ProductCategoryFlatItem { NameWithAncestors = "Drinks / Beers / Local beers", ProductCategoryId = 5 },
new ProductCategoryFlatItem { NameWithAncestors = "Drinks / Beers / Foreingn beers", ProductCategoryId = 6 },
new ProductCategoryFlatItem { NameWithAncestors = "Drinks / Wines", ProductCategoryId = 4 },
new ProductCategoryFlatItem { NameWithAncestors = "Drinks / Wines / Red wines", ProductCategoryId = 7 },
new ProductCategoryFlatItem { NameWithAncestors = "Drinks / Wines / White wines", ProductCategoryId = 8 },
new ProductCategoryFlatItem { NameWithAncestors = "Food", ProductCategoryId = 2 },
};
}
}
public class ProductCategory
{
public int ProductCategoryId { get; set; }
public int? ParentId { get; set; }
public string Name { get; set; }
}
public class ProductCategoryFlatItem
{
public int ProductCategoryId { get; set; }
public string NameWithAncestors { get; set; }
}
}
UPDATE:
I successfully build a tree, and then I am trying to use tree to build breadcrumbs by searching for ancestors, see my code bellow (this is work in progress...)
public interface IProductCategoryExtensions
{
List<ProductCategoryTreeItem> BuildTreeAndGetRoots(List<ProductCategory> allCategories);
List<ProductCategoryFlatItem> CreateComboboxItems(List<ProductCategory> categories);
}
public class ProductCategoryExtensions : IProductCategoryExtensions
{
public List<ProductCategoryTreeItem> BuildTreeAndGetRoots(List<ProductCategory> allCategories)
{
var treeItems = new List<ProductCategoryTreeItem>();
var rootItems = allCategories.Where(x => x.ParentId == null);
foreach (var rootItem in rootItems)
{
treeItems.Add(new ProductCategoryTreeItem
{
Item = rootItem,
Disabled = false,
Parent = null,
Children = GetChildren(allCategories, rootItem)
});
}
return treeItems;
}
private List<ProductCategoryTreeItem> GetChildren(List<ProductCategory> allCategories, ProductCategory productCategory)
{
var children = new List<ProductCategoryTreeItem>();
var childrenTemp = allCategories.Where(x => x.ParentId == productCategory.ProductCategoryId);
foreach (var childTemp in childrenTemp)
{
var child = new ProductCategoryTreeItem
{
Disabled = false,
Item = childTemp,
Children = GetChildren(allCategories, childTemp),
};
children.Add(child);
}
return children;
}
public List<ProductCategoryFlatItem> CreateComboboxItems(List<ProductCategory> categories)
{
var flats = new List<ProductCategoryFlatItem>();
var tree = BuildTreeAndGetRoots(categories);
foreach (var treeItem in tree)
{
flats.Add(CreateFlatItem(treeItem, categories));
if (treeItem.HasChildren)
{
flats.AddRange(GetChildrenFlats(treeItem.Children));
}
}
return flats;
}
private List<ProductCategoryFlatItem> GetChildrenFlats(List<ProductCategoryTreeItem> children)
{
var flatChildren = new List<ProductCategoryFlatItem>();
foreach (var child in children)
{
//if (child.Children != null && child.Children.Count > 0)
// Get
}
return flatChildren;
}
private ProductCategoryFlatItem CreateFlatItem(ProductCategoryTreeItem treeItem, List<ProductCategory> allCategories)
{
var flat = new ProductCategoryFlatItem();
if (treeItem.Parent == null)
{
flat.Description = treeItem.Item.Description;
flat.ProductCategoryId = treeItem.Item.ProductCategoryId;
}
else
{
}
return flat;
}
public List<ProductCategoryTreeItem> BuildTreeAndGetRoots(List<ProductCategory> allCategories)
{
var treeItems = new List<ProductCategoryTreeItem>();
var rootItems = allCategories.Where(x => x.ParentId == null);
foreach (var rootItem in rootItems)
{
treeItems.Add(new ProductCategoryTreeItem
{
Item = rootItem,
Disabled = false,
Parent = null,
Children = GetChildren(allCategories, rootItem)
});
}
return treeItems;
}
}
public class ProductCategoryTreeItem
{
public ProductCategory Item { get; set; }
public bool Disabled { get; set; }
public ProductCategoryTreeItem Parent { get; set; }
public List<ProductCategoryTreeItem> Children { get; set; } = new List<ProductCategoryTreeItem>();
public bool HasChildren
{
get
{
return Children != null && Children.Count > 0;
}
}
}
Sorry this is kinda messy code, but I'll leave the refactoring to you.
Assuming we have two classes:
public class ProductCategory
{
public int ProductCategoryId { get; set; }
public int? ParentId { get; set; }
public string Name { get; set; }
public Dictionary<ProductCategory, int> AncestorsWithHierarchy { get; set; } = new Dictionary<ProductCategory, int>();
}
public class ProductCategoryFlatItem
{
public string NameWithAncestors { get; set; }
public int ProductCategoryId { get; set; }
}
I added AncestorsWithHierarchy to ProductCategory to be able to set up breadcrumb order right.
Then you can do setup a continuous search backwards among ancestors in a recursive way, while adding the hierarchy level to use it for .OrderBy()
var result = new List<ProductCategoryFlatItem>();
Func<ProductCategory, ProductCategory> FindParent = null;
FindParent = thisItem =>
{
var parent = categories.Find(c => c.ProductCategoryId == thisItem.ParentId);
return parent;
};
foreach (var category in categories)
{
int hierarchyLevel = 0;
var parent = FindParent(category);
while (parent != null)
{
category.AncestorsWithHierarchy.Add(parent, hierarchyLevel);
hierarchyLevel++;
parent = FindParent(parent);
}
// Add self since we want it in the breadcrumb
category.AncestorsWithHierarchy.Add(category, -1);
result.Add(new ProductCategoryFlatItem()
{
NameWithAncestors = string.Join(" / ", category.AncestorsWithHierarchy.OrderByDescending(x => x.Value).Select(anc => anc.Key.Name)),
ProductCategoryId = category.ProductCategoryId
});
}
Which gives you your desired result:
However, I would never do this kind of operation during every read. I'm assuming this data will be read much more than it'll be written. So, what I would really do is, to move this logic where you are CRUD'ing to the database and build your breadcrumb there as a new field, and only recalculate if a category changes. This is much better than calculating on every single read request for every single user.
I am trying to seed data and none of my mappings seem to be working. I believe I am following the [textbook examples ][1] from documentation but I must be missing something.
My classes
public class HighSchoolRegistrationModel
{
public long Id{ get; set; }
[Required]
public string SchoolName { get; set; }
[Required]
public string Address { get; set; }
[Required]
[EmailAddress]
public string SchoolEmail { get; set; }
public ICollection<CourseModel> CourseModelsOffered { get; set; }
public ICollection<Student> Students { get; set; }
}
public class Student
{
public long StudentId { get; set; }
public string Name { get; set; }
public long HighSchoolRegistrationModelId { get; set; }
public HighSchoolRegistrationModel HighSchoolRegistrationModel { get; set; }
public Grade CurrentGradeLevel { get; set; }
public ICollection<Guardian> Guardians { get; set; }
public ICollection<Result> Results { get; set; }
public ICollection<CourseInstance> Courses { get; set; }
public ICollection<CourseGrade> CourseGrades { get; set; }
public ICollection<ReportCard> ReportCards { get; set; }
}
public class Result
{
public long ResultId{ get; set; }
public long StudentId { get; set; }
public Student Student { get; set; }
public Exam ExamType { get; set; }
public double Score { get; set; }
}
My context class
// HighSchoolContext, my only context
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<HighSchoolRegistrationModel>().HasData(
new HighSchoolRegistrationModel
{
Id = 1,
SchoolName = "Nouveau Blaise Pascal",
Address = "123 Rue du Ciel",
SchoolEmail = "npb#fauxemails.fr"
}
);
modelBuilder.Entity<CourseModel>().HasData(
new CourseModel()
{
Id = 1,
CourseName = "Maths",
GradeLevel = Grade.Fifth,
HighSchoolRegistrationModelId = 1
},
new CourseModel()
{
Id = 2,
CourseName = "Language",
GradeLevel = Grade.Fifth,
HighSchoolRegistrationModelId = 1
}
);
modelBuilder.Entity<Student>().HasData(
new Student()
{
StudentId = 1,
Name = "Camille Foussoulou",
CurrentGradeLevel = Grade.Fifth,
HighSchoolRegistrationModelId = 1
},
new Student()
{
StudentId = 2,
Name = "Lucas Foussoulou",
CurrentGradeLevel = Grade.Fifth,
HighSchoolRegistrationModelId = 1
}
);
modelBuilder.Entity<Guardian>().HasData(
new Guardian()
{
GuardianId = 1,
Name = "Joseph Foussoulou"
},
new Guardian()
{
GuardianId = 2,
Name = "Jeanne Ntoume"
}
);
modelBuilder.Entity<GuardianStudent>().HasData(
new GuardianStudent() { GuardianId = 1, StudentId = 1},
new GuardianStudent() { GuardianId = 1, StudentId = 2},
new GuardianStudent() { GuardianId = 2, StudentId = 1},
new GuardianStudent() { GuardianId = 2, StudentId = 2}
);
modelBuilder.Entity<Result>().HasData(
new Result()
{
ResultId = 1,
StudentId = 1,
ExamType = Exam.Art,
Score = 77.7
},
new Result()
{
ResultId = 2,
StudentId = 1,
ExamType = Exam.Language,
Score = 77.5
}
...//more results
);
modelBuilder.Entity<Instructor>().HasData(
new Instructor() { InstructorId = 1, Name = "Jacques Alassane" },
new Instructor() { InstructorId = 2, Name = "Alice des Plaines" }
);
modelBuilder.Entity<CourseInstance>().HasData(
new CourseInstance()
{
CourseInstanceId = 1,
CourseModelId = 1,
InstructorId = 1,
},
new CourseInstance()
{
CourseInstanceId = 2,
CourseModelId = 2,
InstructorId = 2,
}
);
modelBuilder.Entity<CourseGrade>().HasData(
new CourseGrade()
{
CourseGradeId = 1,
StudentId = 1,
CourseInstanceId = 1,
Grade = 75.3
},
new CourseGrade()
{
CourseGradeId = 2,
StudentId = 1,
CourseInstanceId = 1,
Grade = 72.3
}
//more grades
);
modelBuilder.Entity<CourseInstanceStudent>().HasData(
new CourseInstanceStudent() { CourseInstanceId = 1, StudentId = 1},
new CourseInstanceStudent() { CourseInstanceId = 1, StudentId = 2},
new CourseInstanceStudent() { CourseInstanceId = 2, StudentId = 1},
new CourseInstanceStudent() { CourseInstanceId = 2, StudentId = 2}
);
}
Yet, when run add migration, update database, start up my app and hit api/Students (standard http get in postman), my Students do not have any Results. Nor any of the other entities in the collection that I meant to seed for that matter. What did I miss?
EDIT
To clarify more, my api:
// StudentsController.cs
[HttpGet]
public async Task<ActionResult<IEnumerable<Student>>> GetStudents()
{
return await _context.Students.ToListAsync();
}
Where I call it in the front end
//StudentService.cs
public async Task<IEnumerable<Student>> GetStudentsAsync()
{
var options = new JsonSerializerOptions()
{
ReferenceHandler = ReferenceHandler.Preserve,
PropertyNameCaseInsensitive = true
};
return await http.GetFromJsonAsync<IEnumerable<Student>>("api/Students", options);
}
The response:
{"$id":"1","$values":[{"$id":"2","studentId":1,"name":"Camille Foussoulou","highSchoolRegistrationModelId":1,"highSchoolRegistrationModel":null,"currentGradeLevel":1,"guardians":null,"results":null,"courses":null,"courseGrades":null,"reportCards":null},{"$id":"3","studentId":2,"name":"Lucas Foussoulou","highSchoolRegistrationModelId":1,"highSchoolRegistrationModel":null,"currentGradeLevel":1,"guardians":null,"results":null,"courses":null,"courseGrades":null,"reportCards":null}]}
The commmands I ran
dotnet ef migrations add InitialCreate -c HighSchoolContext
dotnet ef database update -c HighSchoolContext
Using Sqlite at the moment.
[1]: https://learn.microsoft.com/en-us/ef/core/modeling/relationships?tabs=fluent-api%2Cfluent-api-simple-key%2Csimple-key
It turns out that I had simply forgotten to define what related data I wanted included with the entity I was reading from the database. In this example, to get the Results of the Student I just did this
[HttpGet]
public async Task<ActionResult<IEnumerable<Student>>> GetStudents()
{
return await _context.Students
.Include(s => s.Results)
.ToListAsync();
}
Which is eager loading, as I go on I'll probably explore different loading strategies.
Given the data below, I am trying to write a LINQ statement that will group by ListOfAdmin by id so it will only display one user. I am also checking that the count is not 0. The record one has no ListOfAdmin so that Count==0 should return null but it is displaying records for ListOfAdmin . Also
once I add //.GroupBy(f => f.id) I get the error Cannot implicitly convert type 'System.Collections.Generic.List
All of the other section is working fine.
Once I add ListOfSubscription with no record for ListOfAdmin I get the error
LINQPad Example
class Subscription
{
public int SubscriptionId { get; set; }
public int ParentProductId { get; set; }
public string ParentProductName { get; set; }
public string ChildProductName { get; set; }
public int ChildProductId { get; set; }
public int GroupId { get; set; }
public DateTime? EndDate { get; set; }
public List<admin> ListOfAdmin { get; set; }
}
class SubscriptionViewModel
{
public int SubscriptionId { get; set; }
public int ParentProductId { get; set; }
public string ParentProductName { get; set; }
public string SubscriptionIds { get; set; }
public int GroupId { get; set; }
public List<SubscriptionChildViewModel> ListOfSubscriptionChild { get; set; }
public List<AdminViewModel> ListOfAdmin { get; set; }
}
class SubscriptionChildViewModel
{
public string ChildProductName { get; set; }
public int ChildProductId { get; set; }
}
class AdminViewModel
{
public int id { get; set; }
public string name { get; set; }
}
class admin
{
public int id { get; set; }
public string name { get; set; }
}
void Main()
{
List<Subscription> ListOfSubscription = new List<Subscription>();
List<admin> ListOfAdmin = new List<admin>();
ListOfSubscription.Add(new Subscription() { SubscriptionId = 1, ParentProductId = 4, ChildProductId = 4, ParentProductName = "Product 1", ChildProductName = "Product 1", GroupId = 362,ListOfAdmin= ListOfAdmin });
ListOfAdmin.Clear();
ListOfAdmin.Add(new admin() { id = 1, name= "Mike"});
ListOfAdmin.Add(new admin() { id = 2, name = "Bill" });
ListOfSubscription.Add(new Subscription() { SubscriptionId = 2, ParentProductId = 114, ChildProductId = 1, ParentProductName = "Product 2", ChildProductName = "Product 3", GroupId = 1, ListOfAdmin= ListOfAdmin });
ListOfSubscription.Add(new Subscription() { SubscriptionId = 3, ParentProductId = 114, ChildProductId = 2, ParentProductName = "Product 2", ChildProductName = "Product 4", GroupId = 1, ListOfAdmin = ListOfAdmin });
var groupedSubscriptions = ListOfSubscription.GroupBy(u => u.GroupId);
var result = groupedSubscriptions.Select(grp1 => new
{
GroupId = grp1.Key,
Subscriptions = grp1.GroupBy(subscr => new
{
subscr.ParentProductId,
subscr.ParentProductName,
//subscr.ListOfAdmin
})
.Select(grp2 => new SubscriptionViewModel
{
GroupId = grp1.Key,
ParentProductId = grp2.Key.ParentProductId,
ParentProductName = grp2.Key.ParentProductName,
SubscriptionIds = string.Join(",", grp2.Select(y => y.SubscriptionId)),
ListOfSubscriptionChild = grp2
.Where(subsc => subsc.ChildProductId != grp2.Key.ParentProductId)
.Select(subsc => new SubscriptionChildViewModel
{
ChildProductId = subsc.ChildProductId,
ChildProductName = subsc.ChildProductName
})
.ToList(),
ListOfAdmin = (grp2.SelectMany(y => y.ListOfAdmin).Count()) == 0 ? null : grp2.SelectMany(y => y.ListOfAdmin)
.Select(a => new AdminViewModel
{
id = a.id,
name = a.name
})
//.GroupBy(f => f.id)
.ToList(),
})
});
var x = result.SelectMany((s => s.Subscriptions));
Console.Write(x);
}
Updated: using List<IGrouping<int, AdminViewModel>> I am getting dups.
Let's take a look at the exact error: Cannot implicitly convert type 'System.Collections.Generic.List<System.Linq.IGrouping<int,Program.AdminViewModel>>' to 'System.Collections.Generic.List<Program.AdminViewModel>'.
It is pretty clear: you are trying to assign a value (of type List<IGrouping<int,Program.AdminViewModel>>) that is not of the expected type (List<Program.AdminViewModel>).
You can remedy this by changing SubscriptionViewModel, so that ListOfAdmin will be List<IGrouping<int, AdminViewModel>>, as #itectori suggested.
However, I don't think that's what you're looking for. If I understand correctly, ListOfAdmin should contain, well, the admins. If that is the case, simply select the first item of every IGrouping, like this:
ListOfAdmin = (grp2.SelectMany(y => y.ListOfAdmin).Count()) == 0 ? null : grp2.SelectMany(y => y.ListOfAdmin)
.Select(a => new AdminViewModel
{
id = a.id,
name = a.name
})
.GroupBy(f => f.id)
.Select(g => g.First())
.ToList(),
According to the documentation, GrouBy() returns an object of type IEnumerable<IGrouping<TKey,TElement>>.
In your case,
(grp2.SelectMany(y => y.ListOfAdmin).Count()) == 0 ? null : grp2.SelectMany(y => y.ListOfAdmin)
.Select(a => new AdminViewModel
{
id = a.id,
name = a.name
})
.GroupBy(f => f.id)
.ToList()
return an object of type List<IGrouping<int, AdminViewModel>>
In order for your code to work, you just need to change the type of the SubscriptionViewModel.ListOfAdmin attribute.
class SubscriptionViewModel
{
[...]
public List<IGrouping<int, AdminViewModel>> ListOfAdmin { get; set; }
}
I have an entity Contracts, ListKindWorks and KindWorks.
public partial class Contracts
{
public Contracts()
{
ListKindWorks = new HashSet<ListKindWorks>();
}
public int Id { get; set; }
...
public virtual ICollection<ListKindWorks> ListKindWorks { get; set; }
}
public partial class ListKindWorks
{
public int IdContract { get; set; }
public int IdKindWork { get; set; }
public virtual Contracts IdContractNavigation { get; set; }
public virtual KindWorks IdKindWorkNavigation { get; set; }
}
public partial class KindWorks
{
public KindWorks()
{
ListKindWorks = new HashSet<ListKindWorks>();
}
public int Id { get; set; }
public string Title { get; set; }
public virtual ICollection<ListKindWorks> ListKindWorks { get; set; }
}
I want to load related elements. Something like this pseudocode:
source = model.Contracts
.Select(c => new MyType
{
IdContract = c.Id,
KindWork = new List<Item>
{ Id = KindWorks.Id, Value = KindWorks.Title }
// or
// KindWork = c.ListKindWorks
// .Where(x => x.IdContract == c.Id)
// .Select(y => new Item
// { Id = y.IdKindWork, Value = y.IdKindWorkNavigation.Title })
...
})
.ToList();
public class Item
{
public int Id { get; set; }
public string Value { get; set; }
}
Can I load List<Item> for each Contracts?
If I understand what you are looking for, I create a List for each contract in a dictionary. And here is my result:
var contracts = new List<Contracts>
{
new Contracts { Id = 1 },
new Contracts { Id = 2 },
new Contracts { Id = 3 },
};
var listKindWorks = new List<ListKindWorks>
{
new ListKindWorks { IdContract = 1, IdKindWork = 1 },
new ListKindWorks { IdContract = 1, IdKindWork = 2 },
new ListKindWorks { IdContract = 2, IdKindWork = 2 },
new ListKindWorks { IdContract = 2, IdKindWork = 3 }
};
var kindWorks = new List<KindWorks>
{
new KindWorks { Id = 1, Title = "Title 1" },
new KindWorks { Id = 2, Title = "Title 2" },
new KindWorks { Id = 3, Title = "Title 3" },
};
Dictionary<Contracts, List<Item>> myDic = contracts.Select(
contract => contract).ToDictionary(
contract => contract,
contract => listKindWorks.Where(
listKindWork => listKindWork.IdContract.Equals(contract.Id))
.Select(listKindWork => new Item
{
Id = kindWorks.FirstOrDefault(kindWork => kindWork.Id.Equals(listKindWork.IdKindWork))?.Id?? listKindWork.IdKindWork,
Value = kindWorks.FirstOrDefault(kindWork => kindWork.Id.Equals(listKindWork.IdKindWork))?.Title?? "KindWork not found"
}).ToList());
I obtain this for my test :
Contract1 : Title1, Title2
Contract2 : Title2, Title3
Contract3 : Nothing
IEnumerable<Item> KindWork = c.ListKindWorks
.Select(y => new Item
{
Id = y.IdKindWork,
Value = y.IdKindWorkNavigation.Title
})
IEnumerable<Item> Subject = c.ListSubjects
.Select(y => new Item
{
Id = y.IdSubject,
Value = y.IdSubjectNavigation.Title
})
I have the following list
class Programm
{
public static void Main(string[] args)
{
List<Service> Services =new List<Service>
{
new Service
{
Name = "name1",
Prices = new List<BEPrice>
{
new BEPrice
{
Price = 120,
Quantity = 3
}
}
},
new Service
{
Name = "name2",
Prices = new List<BEPrice>
{
new BEPrice
{
Price = 123,
Quantity = 3
}
}
},
new Service
{
Name = "name3",
Prices = new List<BEPrice>
{
new BEPrice
{
Price = 100,
Quantity = 3
}
}
},
new Service
{
Name = "name4",
Prices = new List<BEPrice>
{
new BEPrice
{
Price = 900,
Quantity = 8
}
}
}
};
}
public class Tariff
{
public string Name { get; set; }
public List<BEPrice> Prices { get; set; }
}
public class Service
{
public string Name { get; set; }
public List<BEPrice> Prices { get; set; }
public Tariff Tariff;
}
public class BEPrice
{
public decimal Price { get; set; }
public int Quantity { get; set; }
}
I want a result as
Tariff-1 -> Name - "blabla", Prices = {
Price1 = {Price = 343, Quantity = 3},
Price2 = {Price = 900, Quantity = 8} }
The tariff first price Price1 343 is a sum of 100, 120, 123 for 3 (Quantity) month.
Here is my unsuccessful attemp
foreach (var groupedPrices in Services.Select(s => s.Prices.GroupBy(p => p.Quantity)))
{
foreach (var p in groupedPrices.Select(x => x.Key))
Console.WriteLine(p);
foreach (var price in groupedPrices)
{
_prices.AddRange(price.Select(p => p));
}
}
Not sure what is name blabla, but this is how you can get prices part
var prices = Services
.SelectMany(arg => arg.Prices)
.GroupBy(arg => arg.Quantity)
.Select(arg => new { Price = arg.Sum(x => x.Price), Quantity = arg.Key })
.ToList();