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();
Related
Here is my previous post.
https://stackoverflow.com/questions/75106799/how-to-get-data-from-3-table-into-1-list/.
It works fine.
But i expect returning value as:
[{ "id": "1f5a6c7c-6168-4ac8-73a5-08daf474a373", "name": "Bag A", "quantity": 10, "category": "Cat-A" }, { "id": "9b8eb0cc-0da4-4b6a-73a6-08daf474a373", "name": "Shirt A", "quantity": 10, "category": "Cat-B" }, { "id": "DB2EE420-A4E5-407A-5F96-08DAF4759F9C", "name": "Shoes A", "quantity": 10, "category": "Cat-C" } ]
I use .net core 6 MVC - code first. Please help me.
I want to return value without "bag", "shirts","shoes". Look like
above:
Well, based on your question, you could achieve by introduing new model which would be containing all property that your "bag", "shirts","shoes" containing. Finally, you need to loop through the existing list item and bind those into new class/model. You can have a try in following way:
Create A new Model for generic List:
public class GenericClass
{
public int Id { get; set; }
public string Name { get; set; }
public int Quantity { get; set; }
public string Category { get; set; }
}
Note: We will use this model to loop over our existing list thus we would bind them into this.
Base Model:
public class GenericClass
{
public int Id { get; set; }
public string Name { get; set; }
public int Quantity { get; set; }
public string Category { get; set; }
}
public class Bags
{
public int Id { get; set; }
public string Name { get; set; }
public int Quantity { get; set; }
public string Category { get; set; }
}
public class Shirts
{
public int Id { get; set; }
public string Name { get; set; }
public int Quantity { get; set; }
public string Category { get; set; }
}
public class Shoes
{
public int Id { get; set; }
public string Name { get; set; }
public int Quantity { get; set; }
public string Category { get; set; }
}
Seed Data Into Model:
List<Bags> listBags = new List<Bags>();
listBags.Add(new Bags() { Id = 101, Name = "Bag A", Quantity = 10, Category = "Cat-A" });
listBags.Add(new Bags() { Id = 102, Name = "Bag B", Quantity = 15, Category = "Cat-A" });
listBags.Add(new Bags() { Id = 103, Name = "Bag C", Quantity = 20, Category = "Cat-A" });
List<Shirts> listShirts = new List<Shirts>();
listShirts.Add(new Shirts() { Id = 101, Name = "Shirt A", Quantity = 10, Category = "Cat-B" });
listShirts.Add(new Shirts() { Id = 102, Name = "Shirt B", Quantity = 15, Category = "Cat-B" });
listShirts.Add(new Shirts() { Id = 103, Name = "Shirt C", Quantity = 20, Category = "Cat-B" });
List<Shoes> listShoes = new List<Shoes>();
listShoes.Add(new Shoes() { Id = 101, Name = "Shirt A", Quantity = 10, Category = "Cat-S" });
listShoes.Add(new Shoes() { Id = 102, Name = "Shirt B", Quantity = 15, Category = "Cat-S" });
listShoes.Add(new Shoes() { Id = 103, Name = "Shirt C", Quantity = 20, Category = "Cat-S" });
Build Custom List:
var genericClass = new List<GenericClass>();
foreach (var item in listBags)
{
var bag = new GenericClass();
bag.Id = item.Id;
bag.Name = item.Name;
bag.Quantity = item.Quantity;
bag.Category = item.Category;
genericClass.Add(bag);
}
foreach (var item in listShirts)
{
var shirt = new GenericClass();
shirt.Id = item.Id;
shirt.Name = item.Name;
shirt.Quantity = item.Quantity;
shirt.Category = item.Category;
genericClass.Add(shirt);
}
foreach (var item in listShoes)
{
var shoes = new GenericClass();
shoes.Id = item.Id;
shoes.Name = item.Name;
shoes.Quantity = item.Quantity;
shoes.Category = item.Category;
genericClass.Add(shoes);
}
Complete Demo:
[HttpGet("GetFrom3TablesWithSameKey")]
public IActionResult GetFrom3TablesWithSameKey()
{
List<Bags> listBags = new List<Bags>();
listBags.Add(new Bags() { Id = 101, Name = "Bag A", Quantity = 10, Category = "Cat-A" });
listBags.Add(new Bags() { Id = 102, Name = "Bag B", Quantity = 15, Category = "Cat-A" });
listBags.Add(new Bags() { Id = 103, Name = "Bag C", Quantity = 20, Category = "Cat-A" });
List<Shirts> listShirts = new List<Shirts>();
listShirts.Add(new Shirts() { Id = 101, Name = "Shirt A", Quantity = 10, Category = "Cat-B" });
listShirts.Add(new Shirts() { Id = 102, Name = "Shirt B", Quantity = 15, Category = "Cat-B" });
listShirts.Add(new Shirts() { Id = 103, Name = "Shirt C", Quantity = 20, Category = "Cat-B" });
List<Shoes> listShoes = new List<Shoes>();
listShoes.Add(new Shoes() { Id = 101, Name = "Shirt A", Quantity = 10, Category = "Cat-S" });
listShoes.Add(new Shoes() { Id = 102, Name = "Shirt B", Quantity = 15, Category = "Cat-S" });
listShoes.Add(new Shoes() { Id = 103, Name = "Shirt C", Quantity = 20, Category = "Cat-S" });
var genericClass = new List<GenericClass>();
foreach (var item in listBags)
{
var bag = new GenericClass();
bag.Id = item.Id;
bag.Name = item.Name;
bag.Quantity = item.Quantity;
bag.Category = item.Category;
genericClass.Add(bag);
}
foreach (var item in listShirts)
{
var shirt = new GenericClass();
shirt.Id = item.Id;
shirt.Name = item.Name;
shirt.Quantity = item.Quantity;
shirt.Category = item.Category;
genericClass.Add(shirt);
}
foreach (var item in listShoes)
{
var shoes = new GenericClass();
shoes.Id = item.Id;
shoes.Name = item.Name;
shoes.Quantity = item.Quantity;
shoes.Category = item.Category;
genericClass.Add(shoes);
}
return Ok(genericClass);
}
Output:
Note: If you still have any concern please have a look on our official documnet here.
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 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 a dictionary defined as
var dataDict = new Dictionary<String, List<RICData>>();
with the RICData class defined as
class RICData
{
public string pubdate { get; set; }
public string settle { get; set; }
public int colorder { get; set; }
}
The following illustrates the data the dictionary dataDict contains -
"TEST1", ("12/01/2015, 100.1, 1", "12/02/2015, 200.1, 2", "12/03/2015, 300.4, 3")
"TEST2", ("12/01/2015, 150.1, 6", "12/02/2015, 200.1, 7")
"TEST3", ("12/01/2015, 250.1, 4", "12/02/2015, 400, 5")
What I would like to do is group the data by date and order by colorder and retun something simlar to what is below
"12/01/2015", ("TEST1, 100.1, 1", "TEST3, 250.1, 4", "TEST2, 150.1, 6")
"12/02/2015", ("TEST1, 200.1, 2", "TEST3, 400, 5", "TEST2, 200.1, 7"
"12/03/2015", ("TEST1, 300.4, 3")
Here's some sample code. I guess I'm not sure how to group this data
var dataDict = new Dictionary<String, List<RICData>>();
var rdList = new List<RICData>();
rdList.Add(new RICData{pubdate = "12/01/2015", settle = "100.1", colorder = 1});
rdList.Add(new RICData{pubdate = "12/02/2015", settle = "110.1", colorder = 2});
rdList.Add(new RICData { pubdate = "12/03/2015", settle = "120.1", colorder = 3 });
dataDict.Add("TEST1", rdList);
var rdList1 = new List<RICData>();
rdList1.Add(new RICData { pubdate = "12/01/2015", settle = "140.1", colorder = 6 });
rdList1.Add(new RICData { pubdate = "12/02/2015", settle = "100.1", colorder = 7 });
dataDict.Add("TEST2", rdList1);
var rdList2 = new List<RICData>();
rdList2.Add(new RICData { pubdate = "12/01/2015", settle = "240.1", colorder = 4 });
rdList2.Add(new RICData { pubdate = "12/02/2015", settle = "200.1", colorder = 5 });
dataDict.Add("TEST3", rdList2);
//?????
var resultGrp = dataDict.GroupBy(p => p.Value.Select(x => x.pubdate));
public class RICData
{
public string PubDate { get; set; }
public string Settle { get; set; }
public int ColorDer { get; set; }
}
public class NewRICData
{
public string Label { get; set; }
public string Settle { get; set; }
public int Colorder { get; set; }
}
var oldDict = new Dictionary<string, List<RICData>>();
var newDict = oldDict.SelectMany(pair => pair.Value.Select(data => new
{
PubDate = DateTime.Parse(data.PubDate),
NewRICData = new NewRICData
{
Label = pair.Key,
Settle = data.Settle,
ColorDer = data.ColorDer
}
}))
.GroupBy(x => x.PubDate.Date)
.ToDictionary(group => group.Key.ToString("d"),
group => group.Select(x => x.NewRICData)
.OrderBy(x => x.ColorDer));
I have two lists. See my code below:
public class Person
{
public string Name { get; set; }
public int ItemOneId { get; set; }
public int ItemTwoId { get; set; }
}
public class Item
{
public int ItemOneId { get; set; }
public int ItemTwoId { get; set; }
}
List<Person> persons = new List<Person>
{
new Person
{
Name = "a",
ItemOneId = 11,
ItemTwoId = 23
},
new Person
{
Name = "c",
ItemOneId = 11,
ItemTwoId = 56
},
new Person
{
Name = "d",
ItemOneId = 109,
ItemTwoId = 59
}
};
List<Item> items = new List<Item>
{
new Item
{
ItemOneId = 11,
ItemTwoId = 56
},
new Item
{
ItemOneId = 1,
ItemTwoId = 2
}
};
I would like to get all persons from persons list where ItemOneId and ItemTwoId don't exist on items list. I have below code - is better solution?
List<Person> result = new List<Person>();
foreach(Person person in persons)
{
if (!items.Any(x => x.ItemOneId == person.ItemOneId && x.ItemTwoId == person.ItemTwoId))
{
result.Add(person);
}
}
Or maybe there is no other solution?
The code below should work!
var result = persons.Where(p => !items.Any(x => x.ItemOneId == p.ItemOneId && x.ItemTwoId == p.ItemTwoId);