This model I would like flat into a view model but the Current Output is not correct it is setting all the ChildProductId to the last value. I am creating one List<SubscriptionViewModel> and then creating multiple SubscriptionViewModel and adding to the collection.
List<Subscription> ListOfSubscriptions = new List<Subscription>();
List<SubscriptionChild> SubscriptionChild = new List<SubscriptionChild>();
SubscriptionChild.Add(new SubscriptionChild() { ChildProductId = 1, ChildProductName = "Child 1" });
SubscriptionChild.Add(new SubscriptionChild() { ChildProductId = 2, ChildProductName = "Child 2" });
ListOfSubscriptions.Add(new Subscription() { SubscriptionId = 1, ParentProductId=1, ParentProductName = "Product 1",ListOfSubscriptionChild= SubscriptionChild });
SubscriptionChild.Clear();
ListOfSubscriptions.Add(new Subscription() { SubscriptionId = 2, ParentProductId = 2, ParentProductName = "Product 2"});
SubscriptionChild.Clear();
SubscriptionChild.Add(new SubscriptionChild() { ChildProductId = 3, ChildProductName = "Child 3" });
SubscriptionChild.Add(new SubscriptionChild() { ChildProductId = 4, ChildProductName = "Child 4" });
ListOfSubscriptions.Add(new Subscription() { SubscriptionId = 3, ParentProductId = 3, ParentProductName = "Product 3", ListOfSubscriptionChild = SubscriptionChild });
List<SubscriptionViewModel> SubscriptionViewModel = new List<SubscriptionViewModel>();
foreach (var Subscription in ListOfSubscriptions)
{
SubscriptionViewModel vm = new SubscriptionViewModel();
vm.SubscriptionId = Subscription.SubscriptionId;
vm.ParentProductId = Subscription.ParentProductId;
vm.ParentProductName = Subscription.ParentProductName;
int count = Subscription.ListOfSubscriptionChild == null ? 0 : Subscription.ListOfSubscriptionChild.Count;
if (count == 0) {
SubscriptionViewModel.Add(vm);
}
else
{
var listOfChild = Subscription.ListOfSubscriptionChild.ToList();
foreach (var item in listOfChild)
{
vm.ChildProductId = item.ChildProductId;
vm.ChildProductName = item.ChildProductName;
SubscriptionViewModel.Add(vm);
}
}
}
foreach (var item in SubscriptionViewModel)
{
Console.WriteLine(string.Format("SubscriptionId{0} ParentProductId-{1} ChildProductId-{2}", item.SubscriptionId, item.ParentProductId, item.ChildProductId));
}
class Subscription
{
public int SubscriptionId { get; set; }
public int ParentProductId { get; set; }
public string ParentProductName { get; set; }
public List<SubscriptionChild> ListOfSubscriptionChild { get; set; }
}
class SubscriptionChild
{
public string ChildProductName { get; set; }
public int ChildProductId { get; set; }
}
class SubscriptionViewModel
{
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; }
}
Current Output
SubscriptionId1 ParentProductId-1 ChildProductId-4
SubscriptionId1 ParentProductId-1 ChildProductId-4
SubscriptionId2 ParentProductId-2 ChildProductId-0
SubscriptionId3 ParentProductId-3 ChildProductId-4
SubscriptionId3 ParentProductId-3 ChildProductId-4
expected outcome
SubscriptionId1 ParentProductId-1 ChildProductId-1
SubscriptionId1 ParentProductId-1 ChildProductId-2
SubscriptionId2 ParentProductId-2 ChildProductId-0
SubscriptionId3 ParentProductId-3 ChildProductId-3
SubscriptionId3 ParentProductId-3 ChildProductId-4
You're overwriting your SubscriptionViewModel for all of your children. You need to create a new one for each child:
foreach (var Subscription in ListOfSubscriptions)
{
int count = Subscription.ListOfSubscriptionChild == null ? 0 : Subscription.ListOfSubscriptionChild.Count;
if (count == 0)
{
SubscriptionViewModel vm = new SubscriptionViewModel();
vm.SubscriptionId = Subscription.SubscriptionId;
vm.ParentProductId = Subscription.ParentProductId;
vm.ParentProductName = Subscription.ParentProductName;
SubscriptionViewModel.Add(vm);
}
else
{
var listOfChild = Subscription.ListOfSubscriptionChild.ToList();
foreach (var item in listOfChild)
{
// Instantiate a new model for each child
SubscriptionViewModel vm = new SubscriptionViewModel();
vm.SubscriptionId = Subscription.SubscriptionId;
vm.ParentProductId = Subscription.ParentProductId;
vm.ParentProductName = Subscription.ParentProductName;
vm.ChildProductId = item.ChildProductId;
vm.ChildProductName = item.ChildProductName;
SubscriptionViewModel.Add(vm);
}
}
}
Related
Given the data below, I am trying to write a LINQ statement that will check if SubscriptionId is null by using (grp2.Select(y => y.SubscriptionId) == null). This must be failing because it will always go into the else section and return ,4 which is not what I am looking for. Is this the correct way to check if this value is null?
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; }
}
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; }
}
class SubscriptionChildViewModel
{
public string ChildProductName { get; set; }
public int ChildProductId { get; set; }
}
void Main()
{
List<Subscription> ListOfSubscription = new List<Subscription>();
ListOfSubscription.Add(new Subscription() { SubscriptionId = null, ParentProductId = 4, ChildProductId = 4, ParentProductName = "Product 1", ChildProductName = "Product 1", GroupId = 362, });
ListOfSubscription.Add(new Subscription() { SubscriptionId = 2, ParentProductId = 114, ChildProductId = 1, ParentProductName = "Product 2", ChildProductName = "Product 3", GroupId = 1, });
ListOfSubscription.Add(new Subscription() { SubscriptionId = 3, ParentProductId = 114, ChildProductId = 2, ParentProductName = "Product 2", ChildProductName = "Product 4", GroupId = 1, });
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,
})
.Select(grp2 => new SubscriptionViewModel
{
GroupId = grp1.Key,
ParentProductId = grp2.Key.ParentProductId,
ParentProductName = grp2.Key.ParentProductName,
SubscriptionIds = (grp2.Select(y => y.SubscriptionId) == null) ? null : (string.Format("{0},{1}", string.Join(",", grp2.Select(y => y.SubscriptionId)), grp2.Key.ParentProductId))
})
});
var x = result.SelectMany((s => s.Subscriptions));
Console.Write(x);
}
Change your logic
(grp2.Select(y => y.SubscriptionId) == null)
to
grp2.Where(y => y.SubscriptionId == null).Count() > 0
Remove that bracket y.SubscriptionId)
This could work for you, to work with nulleables you can use "HasValue" instead of directly comparing with null.
SubscriptionIds = (grp2.Select( y => y.SubscriptionId.HasValue ) == null) ? null : (string.Format("{0},{1}", string.Join(",", grp2.Select(y => y.SubscriptionId.HasValue)), grp2.Key.ParentProductId))
Microsoft suggests using HasValue for nulleables types
This question already has answers here:
How to Sort a List<T> by a property in the object
(23 answers)
Closed 4 years ago.
I have the following classes.
public class Response
{
List<Make> Makes { get; set; }
public Response()
{
this.Makes = new List<Make>();
}
}
public class Make
{
public string Name { get; set; }
public List<Agent> Agents { get; set; }
public Make()
{
this.Agents = new List<Agent>();
}
}
public class Agent
{
public int Id { get; set; }
public string Name { get; set; }
public List<Offer> Offers { get; set; }
public Agent()
{
this.Offers = new List<Offer>();
}
}
public class Offer
{
public int Id { get; set; }
public List<Model> Models { get; set; }
public Offer()
{
this.Models = new List<Model>();
}
}
public class Model
{
public string Name { get; set; }
public Price Price { get; set; }
public Model()
{
this.Price = new Price();
}
}
public class Price
{
public decimal Total { get; set; }
public decimal Vat { get; set; }
}
Using linq how can I get a list of Makes, that are ordered by the cheapest model first. Also, I want the models for each agent to be ordered by the cheapest first.
The easy way is to put the data into a flat object like a datatable and then sort :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
namespace ConsoleApplication98
{
class Program
{
static void Main(string[] args)
{
Response response = new Response() {
Makes = new List<Make>() {
new Make() {
Name = "AAA", Agents = new List<Agent>() {
new Agent() {
Id = 123, Name = "SSS", Offers = new List<Offer>() {
new Offer() {
Id = 100, Models = new List<Model>() {
new Model() { Name = "TTT", Price = new Price() { Total = 1.0M, Vat = 2.0M}},
new Model() { Name = "UUU", Price = new Price() { Total = 2.0M, Vat = 3.0M}},
},
},
new Offer() {
Id = 200, Models = new List<Model>() {
new Model() { Name = "TTT", Price = new Price() { Total = 1.0M, Vat = 2.0M}},
new Model() { Name = "UUU", Price = new Price() { Total = 2.0M, Vat = 3.0M}}
}
}
}
},
new Agent() {
Id = 456, Name = "SST", Offers = new List<Offer>() {
new Offer() {
Id = 100, Models = new List<Model>() {
new Model() { Name = "TTT", Price = new Price() { Total = 1.0M, Vat = 2.0M}},
new Model() { Name = "UUU", Price = new Price() { Total = 2.0M, Vat = 3.0M}},
},
},
new Offer() {
Id = 200, Models = new List<Model>() {
new Model() { Name = "TTT", Price = new Price() { Total = 1.0M, Vat = 2.0M}},
new Model() { Name = "UUU", Price = new Price() { Total = 2.0M, Vat = 3.0M}}
}
}
}
}
}
},
new Make() {
Name = "AAB", Agents = new List<Agent>() {
new Agent() {
Id = 123, Name = "SSS", Offers = new List<Offer>() {
new Offer() {
Id = 100, Models = new List<Model>() {
new Model() { Name = "TTT", Price = new Price() { Total = 1.0M, Vat = 2.0M}},
new Model() { Name = "UUU", Price = new Price() { Total = 2.0M, Vat = 3.0M}},
},
},
new Offer() {
Id = 200, Models = new List<Model>() {
new Model() { Name = "TTT", Price = new Price() { Total = 1.0M, Vat = 2.0M}},
new Model() { Name = "UUU", Price = new Price() { Total = 2.0M, Vat = 3.0M}}
}
}
}
},
new Agent() {
Id = 456, Name = "SST", Offers = new List<Offer>() {
new Offer() {
Id = 100, Models = new List<Model>() {
new Model() { Name = "TTT", Price = new Price() { Total = 1.0M, Vat = 2.0M}},
new Model() { Name = "UUU", Price = new Price() { Total = 2.0M, Vat = 3.0M}},
},
},
new Offer() {
Id = 200, Models = new List<Model>() {
new Model() { Name = "TTT", Price = new Price() { Total = 1.0M, Vat = 2.0M}},
new Model() { Name = "UUU", Price = new Price() { Total = 2.0M, Vat = 3.0M}}
}
}
}
}
}
}
}
};
DataTable dt = new DataTable();
dt.Columns.Add("Make Name", typeof(string));
dt.Columns.Add("Agent ID", typeof(int));
dt.Columns.Add("Agent Name", typeof(string));
dt.Columns.Add("Offer ID", typeof(int));
dt.Columns.Add("Model Name", typeof(string));
dt.Columns.Add("Total", typeof(decimal));
dt.Columns.Add("Vat", typeof(decimal));
foreach (Make make in response.Makes)
{
string makeName = make.Name;
foreach (Agent agent in make.Agents)
{
int agentID = agent.Id;
string agentName = agent.Name;
foreach (Offer offer in agent.Offers)
{
int offerID = offer.Id;
foreach (Model model in offer.Models)
{
string modelName = model.Name;
decimal vat = model.Price.Vat;
decimal total = model.Price.Total;
dt.Rows.Add(new object[] {
makeName,
agentID,
agentName,
offerID,
modelName,
vat,
total
});
}
}
}
}
dt = dt.AsEnumerable().OrderBy(x => x.Field<decimal>("Total")).CopyToDataTable();
}
}
public class Response
{
public List<Make> Makes { get; set; }
public Response()
{
this.Makes = new List<Make>();
}
}
public class Make
{
public string Name { get; set; }
public List<Agent> Agents { get; set; }
public Make()
{
this.Agents = new List<Agent>();
}
}
public class Agent
{
public int Id { get; set; }
public string Name { get; set; }
public List<Offer> Offers { get; set; }
public Agent()
{
this.Offers = new List<Offer>();
}
}
public class Offer
{
public int Id { get; set; }
public List<Model> Models { get; set; }
public Offer()
{
this.Models = new List<Model>();
}
}
public class Model
{
public string Name { get; set; }
public Price Price { get; set; }
public Model()
{
this.Price = new Price();
}
}
public class Price
{
public decimal Total { get; set; }
public decimal Vat { get; set; }
}
}
It would be easier to verify if you'd provided sample values and the desired result, but here's my take on getting the Makes ordered using a LINQ one-liner:
response.Makes.OrderBy(
make => make.Agents.Select(
agent => agent.Offers.Min(
offer => offer.Models.OrderBy(model => model.Price.Total)
.First().Price.Total)));
Here's the flow (the inner bullets enable the outer bullets):
Get list of Makes
For each Make, select list of Agents
For each Agent, select the minimum offer
For each offer, order by the total price
Select the first (lowest) offer
For each Agent, the minimum offer is now selected
The makes can now be ordered by the minimum offer it contains
I'm not absolutely certain that the flow above makes sense, but give the implementation a shot!
I have two lists. There are only one field difference. How to fill the lists with each other.
[Serializable()]
public class Lst1
{
public string filed1 { get; set; }
public Int16 filed2 { get; set; }
.
.
.
public Boolean filed100 { get; set; }
}
[Serializable()]
public class Lst2
{
public string filed1 { get; set; }
public Int16 filed2 { get; set; }
.
.
.
public Boolean filed100 { get; set; }
public string filed101 { get; set; }
}
List<Lst1> Lst1_ = new List<Lst1>();
List<Lst2> Lst2_ = new List<Lst2>();
I fill out lists from files.
then,I need to fill out the list two from list one,There are many fields And I do not want to use the foreach loop.
It should be remembered that my previous class was already built and serialized and stored in a file. And now I need to transfer the previous information to the second class structure.
I do not want to use this loop!
foreach (var t in Lst1_)
{
Lst2_.Add(new lst2
{
filed1 = t.filed1,
filed2 = t.filed2,
.
.
.
filed100 = t.filed100,
filed101 = "kk"
}
}
Is this what you want?
class Lst1
{
public string filed1 { get; set; }
public string filed2 { get; set; }
public string filed3 { get; set; }
public string filed4 { get; set; }
public string filed5 { get; set; }
}
class Lst2
{
public string filed1 { get; set; }
public string filed2 { get; set; }
public string filed3 { get; set; }
public string filed4 { get; set; }
public string filed5 { get; set; }
public string filed6 { get; set; }
}
void CopyData()
{
// test data
List<Lst1> Lst1_ = new List<Lst1>()
{
new Lst1()
{
filed1 = "1",
filed2 = "2",
filed3 = "3",
filed4 = "4",
filed5 = "5",
},
new Lst1()
{
filed1 = "6",
filed2 = "7",
filed3 = "8",
filed4 = "9",
filed5 = "10",
},
};
List<Lst2> Lst2_ = new List<Lst2>();
foreach (var item in Lst1_)
{
Type type1 = item.GetType();
PropertyInfo[] properties1 = type1.GetProperties();
var current = new Lst2();
Type type2 = current.GetType();
PropertyInfo[] properties2 = type2.GetProperties();
int k = 0;
foreach (PropertyInfo property in properties1)
{
var value = property.GetValue(item, null);
int n;
bool isNumeric = int.TryParse(value.ToString(), out n);
if (!isNumeric)
value = "Your desired value";
properties2[k].SetValue(current, value);
k++;
}
Lst2_.Add(current);
}
}
It copies everything from list 1 to list2.
No need to waste your time and money, AutoMapper can do it for you with only 2 lines of code:
using AutoMapper;
namespace ConsoleApp39
{
class Program
{
static void Main (string[] args)
{
// fill list1 with data
var list1 = new List1
{
Field1 = "test",
Field2 = 5,
Field3 = false,
};
// 1) configure auto mapper
Mapper.Initialize (cfg => cfg.CreateMap<List1, List2> ());
// 2) create list2 and fill with data from list1
List2 list2 = Mapper.Map<List2> (list1);
// fill extra fields
list2.Field4 = new byte[] { 1, 2, 3 };
}
}
public class List1
{
public string Field1 { get; set; }
public int Field2 { get; set; }
public bool Field3 { get; set; }
}
public class List2
{
public string Field1 { get; set; }
public int Field2 { get; set; }
public bool Field3 { get; set; }
public byte[] Field4 { get; set; } // extra field
}
}
Do Lst1 can inheritance from Lst2?
Something like this,
the two lists:
[Serializable()]
public class Lst1
{
public string filed1 { get; set; }
public int filed2 { get; set; }
public bool filed100 { get; set; }
}
[Serializable()]
public class Lst2 : Lst1
{
public string filed101 { get; set; }
}
and one print extension
public static class CExtensions
{
public static string PropertyList(this Lst1 obj)
{
var props = obj.GetType().GetProperties();
var sb = new StringBuilder();
foreach (var p in props)
{
sb.AppendLine(p.Name + ": " + p.GetValue(obj, null));
}
return sb.ToString();
}
}
then using it:
class Program
{
static void Main(string[] args)
{
const int I = 15;
try
{
//init first list
List<Lst1> Lst1_ = new List<Lst1>();
Init(Lst1_);
//print it
Console.WriteLine("Lst1_");
Console.WriteLine(new string('-', I));
Lst1_.ForEach(x => Console.WriteLine(x.PropertyList()));
Console.WriteLine(new string('=', I));
Console.ReadKey();
//init second list
List<Lst1> Lst2_ = Lst1_.Cast<Lst1>().ToList(); //equivalent of two next lines
//List<Lst1> Lst2_ = new List<Lst2>().ConvertAll(x => (Lst1)x);
//Lst2_.AddRange(Lst1_);
//add one more
Lst2_.Add(new Lst2
{
filed1 = "101",
filed2 = 202,
filed100 = true,
filed101 = "10100"
});
//and print
Console.WriteLine("Lst2_");
Console.WriteLine(new string('-', I));
Lst2_.ForEach(x => Console.WriteLine(x.PropertyList()));
Console.WriteLine(new string('=', I));
Console.ReadKey();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
Console.ReadKey();
}
}
private static void Init(List<Lst1> lst_)
{
for (int i = 1; i <= 3; i++)
{
lst_.Add(new Lst1
{
filed1 = i.ToString(),
filed2 = 2 * i,
filed100 = i % 2 == 0
});
}
}
}
enjoy =)
Please check from Json output i wanted using JavaScriptSerializer. Then check class helper i created using json2csharp.com. Problem is in controller. I am not getting correct output as per my required Jason. I am doing correct in controller? Where the problem can be? Please ask question if you want to know something specific, sorry its hard to describe more clearly.
Helper Class Code:
public class ItemsFromFile
{
public string ASIN { get; set; }
public string Title { get; set; }
public List<Product> products { get; set; }
}
public class ItemsDeatails
{
public List<ItemsFromFile> ItemsFromFile { get; set; }
}
public class File
{
public string nameLocator { get; set; }
public ItemsDeatails itemsDeatails { get; set; }
}
public class RootObject
{
public string Token { get; set; }
public File file { get; set; }
}
Controller code:
if (type == "Salefreaks")
{
var token = ctx.BulkStores.FirstOrDefault(x => x.StoreName == store && x.Type == 1).Token;
var ItemsFromFile = new ItemsFromFile()
{
products = new List<Product>()
};
var ItemsDeatails = new ItemsDeatails()
{
};
var File = new File()
{
nameLocator = "testimport1"
};
var RootObject = new RootObject()
{
Token = token
};
var singleItems = ctx.BulkScannedItems.Where(x => x.UserSellerScanRequestId == id).ToList();
foreach (var item in singleItems)
{
ItemsFromFile.products.Add(new Product { ASIN = item.ASIN, Title = item.EbayTitle });
}
var json = new JavaScriptSerializer().Serialize(RootObject);
}
Required Json Output code:
{
"Token": "7f3099b0-36b1",
"file": {
"nameLocator": "testimport1",
"itemsDeatails": {
"ItemsFromFile": [
{
"ASIN": "B011KVFT9Y",
"Title": "Disney Batman Durable Party Beach Outdoor Adventure Camp Chair w/ Storage Bag"
},
{
"ASIN": "B01D4KRBW2",
"Title": "High Quality Diy Oil Painting Paint Number Kit Theme-Romantic Street A Frameless"
}
]
}
}
}
You can initialize internal objects in the code in the constructor as well.
public class RootObject
{
public string Token { get; set; }
public File file { get; set; }
}
public class File
{
public File()
{
this.itemsDeatails = new ItemsDeatails();
}
public string nameLocator { get; set; }
public ItemsDeatails itemsDeatails { get; set; }
}
public class ItemsDeatails
{
public ItemsDeatails(){
this.ItemsFromFile = new List<ItemsFromFile>();
}
public List<ItemsFromFile> ItemsFromFile { get; set; }
}
public class ItemsFromFile
{
public ItemsFromFile(){
this.products = new List<Product>();
}
public List<Product> products { get; set; }
}
public class Product {
public string ASIN { get; set; }
public string Title { get; set; }
}
Initialize your items properly. And create Root Object from the ground up.
Populate the internal classes first and then later ones.
var itemDetails = new ItemsDeatails();
itemDetails.ItemsFromFile = new ItemsFromFile();
var singleItems = ctx.BulkScannedItems.Where(x => x.UserSellerScanRequestId == id).ToList();
foreach (var item in singleItems)
{
itemDetails.ItemsFromFile.products.Add(new Product { ASIN = item.ASIN, Title = item.EbayTitle });
}
var fl = new File(){
nameLocator = "testimport1",
itemsDeatails = itemDetails
}
var token = ctx.BulkStores.FirstOrDefault(x => x.StoreName == store && x.Type == 1).Token;
var root = new RootObject()
{
Token = token,
file = fl
}
var json = new JavaScriptSerializer().Serialize(root);
Ensure that all your objects are assigned appropriately.
var token = ctx.BulkStores.FirstOrDefault(x => x.StoreName == store && x.Type == 1).Token;
var RootObject = new RootObject() {
Token = token,
file = new File() {
nameLocator = "testimport1",
itemsDeatails = new ItemsDeatails() {
ItemsFromFile = new List<ItemsFromFile>()
}
}
};
var itemsFromFile = new ItemsFromFile();
itemsFromFile.products = new List<Product>();
var singleItems = ctx.BulkScannedItems.Where(x => x.UserSellerScanRequestId == id).ToList();
foreach (var item in singleItems) {
itemsFromFile.products.Add(new Product { ASIN = item.ASIN, Title = item.EbayTitle });
}
RootObject.file.itemsDeatails.ItemsFromFile.Add(itemsFromFile);
var json = new JavaScriptSerializer().Serialize(RootObject);
That being said, it appears that you do not need the list of products inside of the ItemsFromFile class. This definition likely makes more sense:
public class ItemsFromFile {
public string ASIN { get; set; }
public string Title { get; set; }
}
Then your code would be something like this:
var token = ctx.BulkStores.FirstOrDefault(x => x.StoreName == store && x.Type == 1).Token;
var RootObject = new RootObject() {
Token = token,
file = new File() {
nameLocator = "testimport1",
itemsDeatails = new ItemsDeatails() {
ItemsFromFile = new List<ItemsFromFile>()
}
}
};
var singleItems = ctx.BulkScannedItems.Where(x => x.UserSellerScanRequestId == id).ToList();
foreach (var item in singleItems) {
RootObject.file.itemsDeatails.ItemsFromFile.Add(new ItemsFromFile { ASIN = item.ASIN, Title = item.EbayTitle });
}
I have two classes: Group and Item.
public class Group
{
public string Name{ get; set; }
public List<Item> ItemList { get; set; }
}
And then Item
public class Item
{
public int ID{ get; set; }
public string Name{ get; set; }
public string Description{ get; set; }
public Group ItemGroup {get;set;}
}
Each group show have a set of items.
The following code is meant to get the list of items of a particular group, and it works when the ItemGroup in the Items class is set to type string, but not as a type Group.
public IEnumerable<Item> GetItemByGroup(string group)
{
return repository.GetAllItems().Where(
p => string.Equals(p.ItemGroup, group, StringComparison.OrdinalIgnoreCase));
}
How to change the code to get the list of items in a group by its Name property which is set in the Group class.
And how do I set a list/collection of Items in the Group class
I think this should work. Give it a hit
public IEnumerable<Item> GetItemByGroup(string group)
{
return repository.GetAllItems().Where(p =>p.ItemGroup.Name.Equals(group));
}
Update
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
List<Item> list = new List<Item>();
Item i = new Item()
{
ID = 1,
Name = "Amit",
Description = "Test",
ItemGroup = new Group() { Name = "A" }
};
list.Add(i);
i = new Item()
{
ID = 2,
Name = "Amit1",
Description = "Test1",
ItemGroup = new Group() { Name = "A1" }
};
list.Add(i);
i = new Item()
{
ID = 3,
Name = "Amit11",
Description = "Test11",
ItemGroup = new Group() { Name = "A11" }
};
list.Add(i);
i = new Item()
{
ID = 4,
Name = "Amit111",
Description = "Test111",
ItemGroup = new Group() { Name = "A111" }
};
list.Add(i);
i = new Item()
{
ID = 9,
Name = "Amit4a",
Description = "Test4a",
ItemGroup = new Group() { Name = "A111" }
};
list.Add(i);
i = new Item()
{
ID = 5,
Name = "Amit5",
Description = "Test5",
ItemGroup = new Group() { Name = "A111" }
};
list.Add(i);
i = new Item()
{
ID = 6,
Name = "Amit6",
Description = "Test6",
ItemGroup = new Group() { Name = "A111" }
};
list.Add(i);
var list1 = list.Where(p => p.ItemGroup.Name.Equals("A111"));
// Console.Write(list1.Count());
foreach (var item in list1)
{
Console.WriteLine(string.Format("ID: {0} Name: {1} Description: {2} Group: {3}",item.ID,item.Name,item.Description,item.ItemGroup.Name));
}
Console.Read();
}
}
public class Group
{
public string Name { get; set; }
}
public class Item
{
public int ID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public Group ItemGroup { get; set; }
}
}