WPF Treeview using linq to entities multiple relations - c#

I don't know what I'm missing on this:
I have this relationship in my EDM- (can't load a picture yet)
Category_1__many RecipeCategory_many__1_Recipe
Basically every recipe has one or more categories and every category can have 0 or more recipes
Here's my code:
private void LoadData()
{
List<Category> Categories = new List<Category>();
List<Recipe> Recipes = new List<Recipe>();
var ctx = new MaWEntities();
var query = from x in ctx.Categories select x;
Categories = query.ToList<Category>();
foreach (Category c in Categories)
{
TreeViewItem TVP = new TreeViewItem() { Header = c.CategoryName.ToString() };
var qq = from xx in ctx.RecipeCategories.Where(o => o.CategoryId == c.CategoryId) select xx;
foreach (var rc in qq)
{
TreeViewItem TVC = new TreeViewItem() { Header = rc.Recipe.RecipeName.ToString() };
TVP.Items.Add(TVC);
//TVP.IsExpanded = true;
}
}
}
What I am trying to accomplish is a treeview whose parent nodes are the categoryname and child nodes are the recipe name. I know how drill into a relational table from a base table (Recipe to RecipeCategory) using Linq. There MUST also be a way to traverse again to the Category table too. I should also mention that even if the Category does not have any Recipes I still want to see the Category Name as a parent in the treeview.

I found that my problem in this scenario was not that my code wasn't working; rather that I neglected to ever add the treeview items to my treeview. Also, this addition needs to be done after the foreach loop. List Categories = new List();
List Recipes = new List();
var ctx = new MaWEntities();
var query = from x in ctx.Categories select x;
Categories = query.ToList<Category>();
foreach (Category c in Categories)
{
TreeViewItem TVP = new TreeViewItem() { Header = c.CategoryName.ToString() };
var query2 = from xx in ctx.RecipeCategories.Where(o => o.CategoryId == c.CategoryId) select xx;
foreach (var rc in query2)
{
TreeViewItem TVC = new TreeViewItem() { Header = rc.Recipe.RecipeName.ToString() };
TVP.Items.Add(TVC);
}
tvwRecipe.Items.Add(TVP);
}

Related

Sorting a list if internal list is empty

I have a list inside of another list. I need to add to the list only those elements whose internal list is not empty. The data is pulled from the server. The code contains 4 lists, Each inside of another - Companies - Shops - Campaigns - Coupons. I need to check if the Coupons list is not empty and add the elements related to that. I would be very thankfull if someone could help with that.
foreach (var row in Companies)
{
reportData.companies.Add(new Companies { ID = row.Id, name = row.BrandName });
var Shops = logicService.CompanyShopService.GetShopsByCompany(row.Id);
var Campaigns = logicService.CampaignService.GetCampaignsByCompany(row.Id);
foreach (var shop in Shops)
{
reportData.companies.Where(item => item.ID == shop.ClientID).FirstOrDefault().shops.Add(new Distribution_Shops { Id = shop.Id, Name = shop.Name });
var shop_campaigns = Campaigns.Where(item => item.ShopID == shop.Id);
foreach (var campaign in shop_campaigns)
{
var coupons = logicService.CouponsService.GetAllByCampaign(campaign.Id, false);
foreach (var company in reportData.companies)
{
foreach (var tmp_shop in company.shops)
{
if (tmp_shop.Id == shop.Id)
{
tmp_shop.campaigns.Add(new Distribution_Campaign { Id = campaign.Id, Name = campaign.CampaignName, coupons = coupons});
}
}
}
}
}
}

How can I create a list inside a list with a foreach in c# ?

In other words I need all the elements of list "Categories" to be the "Parent" and elements of list "commodities" be the children.
Example
public string GetCommodities()
{
List<dynamic> categories = new List<dynamic>();
List<dynamic> commodities = new List<dynamic>();
foreach (var comcat in QuickQuoteRepo.CommodityCategories.All().OrderBy(o => o.Order))
{
categories.Add(new
{
comcat.Category,
});
foreach (var com in comcat.Commodities.OrderBy(o => o.Name))
{
commodities.Add(new
{
com.Name,
});
}
}
var response = new JavaScriptSerializer().Serialize(commodities);
return response;
}
And see if it's possible to all commodities names inside each category, within this foreach.
I tried adding a dynamic list such as:
dynamic listOfElements = new { CAT = categories, COMM = commodities };
But it does't return elemnts as parents or dependency of categories. Is the same as adding
commodities.Add(new
{
comcat.Category,
com.Name,
});
public string GetCommodities()
{
List<dynamic> categoryCommodityList = new List<dynamic>();
foreach (var comcat in QuickQuoteRepo.CommodityCategories.All().OrderBy(o => o.Order))
{
var allCommodities = comcat.Commodities.OrderBy(o => o.Name).Select(com => com.Name).ToList();
categoryCommodityList.Add(new { Catagory = comcat.Category, Items = allCommodities } );
}
return new JavaScriptSerializer().Serialize(categoryCommodityList);
}
You class structure does not support parent-child relationships. I mean, if what you want is that each Category holds a list of commodities, then you would need something like this:
var result = from c in comcat
select new { Category = c, Commoddities = c.Commoddities};
This will return a hierarchy of Categories including all Commodities underneath it.
If you are just receiving a flat data set, then you need something like this:
var result = from c in comcat
select new { Category = c,
Commoddities = c.Where(x=>x.Category.Name == c.Name).Select(x=>x.Commodity) };
Hopefully you get the idea...

Create Treeview depending on DataGridView in C#

I get data from tow database, db1,db2, then Now I want to create treeView for the data in the resulting datagridview; in datagrid view there are: id, name, director,the first record is the prim director, that mean he has not up director(he is owner), each record has no other record or has more records(child), and each child has grandchild and so on, this scenario Just Like in the this page:
I want to create treeview (parent and child and grandchild and so on), depending on xml file
when i used this snippet after some :
void setTree()
{
{
foreach(DataGridViewRow dt in DataGridView1.Rows)
{
var per = this.DataGridView1.Rows.Cast<DataGridViewRow>().Select(n => new person
{
name = dt.Cells[0].Value.ToString(),
Sex = dt.Cells[1].Value.ToString(),
Status = dt.Cells[2].Value.ToString(),
child = dt.Cells[3].Value.ToString(),
id = dt.Cells[4].Value.ToString(),
father = dt.Cells[5].Value.ToString()
}).ToList();
var rootTreeNode = GetTree(per, "").First();.........(1)
treeView1.Nodes.Add(rootTreeNode);
}
}
}
private TreeNode[] GetTree(List<person> per, string parent)
{
return per.Where(p => p.father == parent).Select(p =>
{
var node = new TreeNode(p.name);
node.Tag = p.id;
node.Nodes.AddRange(GetTree(per, p.id));
return node;
}).ToArray();
}
Now, when I use this code, I get error at mark(1),it say:Additional information: Sequence contains no elements.
thank you
after several readings in internet and attempts to solve this small problem, I successed finally.
this is the solution:
{
.............
TreeNode tn = new TreeNode(this.DataGridView2.Rows[0].Cells[0].Value.ToString());//text
tn.Tag = this.DataGridView2.Rows[0].Cells[4].Value.ToString();// id
tn.Name = this.DataGridView2.Rows[0].Cells[5].Value.ToString();//directorid
treeView1.Nodes.Add(tn);
settree(tn);
}
public void settree(TreeNode ns)
{
foreach (DataGridViewRow dr in DataGridView2.Rows)
{
if (dr.Cells[5].Value.ToString() == ns.Tag.ToString())
{
TreeNode tsn = new TreeNode(dr.Cells[0].Value.ToString());
tsn.Tag = dr.Cells[4].Value.ToString();
tsn.Name = dr.Cells[5].Value.ToString();
ns.Nodes.Add(tsn);
settree(tsn);
}
}
}
i will be happy if you benefit from this code.

Populating RadMenu Dynamically from Code Behind

I am trying to dynamically populate a Telerik Radmenu control in my code behind. I'm having a really hard time with it. I need to be able to bind my categories to my root elements and attributes to the child elements. I really am lost on this. If even someone has a suggestion of a better way to do this, even if it's with a different type of menu I would be very happy to try it out. Thanks in advance.
**EDIT my code has changed.
protected void createFilter(int categoryid)
{
// check cateogyrid
//get list of proudct id
List<int> productIds = new List<int>();
DataRow[] productRow = CategoriesProductsData.Tables["Products"].Select("Category_ID = " + 573);
productIds = productRow.Select(p => int.Parse(p["Product_ID"].ToString())).ToList();
//get attributes
ITCProductService pService = new TCProductServiceClient();
var productTuples = (pService.GetProductsAttributes(productIds));
List<Tuple<int, CustomAttribute>> customAttributes = new List<Tuple<int, CustomAttribute>>();
foreach (var productTuple in productTuples)
{
foreach (var attributeTuple in productTuple.m_Item2)
{
var customAttribute = new Tuple<int, CustomAttribute>(productTuple.m_Item1, new CustomAttribute(attributeTuple));
customAttributes.Add(customAttribute);
}
}
List<CustomAttributeCategory> categories = new List<CustomAttributeCategory>();
var categoryTuples = customAttributes.Select(a => a.Item2).Select(a => a.Attribute.Category).Distinct();
foreach (var categoryTuple in categoryTuples)
{
var category = new CustomAttributeCategory(categoryTuple);
var attributeByCategory = customAttributes.Select(a => a.Item2).Where(b => b.Attribute.CategoryId == categoryTuple.AttributeCategoryId).Distinct();
foreach (var attributeTuple in attributeByCategory)
{
var attribute = new CustomAttribute(attributeTuple.Attribute);
var attributeProductIds = customAttributes.Where(a => a.Item2.Attribute.AttributeId == attributeTuple.Attribute.AttributeId).Select(a => a.Item1).ToList();
attribute.ProductIds = attributeProductIds;
category.Attributes.Add(attribute);
}
categories.Add(category);
foreach (var cat in categories)
{
var itemCategory = new RadMenuItem(cat.Category.Name.ToString());
handsetMenu.Items.Add(itemCategory);
var itemAttribute = new RadMenuItem(cat.Attributes.ToString());
handsetMenu.Items.Add(itemAttribute);
}
}
}
<%--RAD MENU--%>
<telerik:RadMenu ID="handsetMenu" runat="server" ShowToggleHandle="true">
</telerik:RadMenu>
I don't think ItemDataBound is the correct place to add child items.
Do you want to add the same child items under each of the root menu items?
Try doing it in the DataBound event (which fires after all itemDataBound events have completed) by iterating all RadMenu items.

Saving values into List in a class by using LINQ

I have a class Item with a string List ImagesUrl property:
public class Item
{
string Name { get; set; }
List<string> ImagesUrl { get; set; }
..
}
And I want to parse a XML file and save each node item into var items. In node item there are nodes img1, .. , img5 and right these I want to save into the Img property by using LINQ command like this:
var items = from item in xmlDocument.Descendants("item")
select new Item
{
Name = item.Element("name").Value,
ImagesUrl = item.Element("img1").Value, //....?
..
};
How you can see, I don't know how I could save the img1..5 values in LINQ. Could someone help me?
var items = from item in xmlDocument.Descendants("item")
select new Item
{
Name = item.Element("name").Value,
ImagesUrl = Enumerable.Range(1,5).Select(x => item.Element("img"+x).Value).ToList();
};
Code is self-explanatory here.
Universal solution independent on count of imgX elements
var items = from item in Xml.Descendants("item")
select new Item
{
Name = item.Element("name").Value,
ImagesUrl = item.Elements()
.Where(e => e.Name.LocalName.StartsWith("img"))
.Select(e => e.Value)
.ToList()
};

Categories

Resources