I have a List of "Person" object:
public class Person
{
public Int32 Id { get; set; }
public String Name { get; set; }
public Document oDocument { get; set; }
}
And also there is Document class.
public class Document
{
public String Type { get; set; }
public String Code { get; set; }
}
I need to populate a DataGridView with that list showing some just two columns:Name(Person) and DocumentCode (Document)
I used this code, but I dont get what I want.
dgvPersona.DataSource = list;
You need to select an anonymous type object (to project required fields) and then bind that to your gridview like:
var list = (from p in persons
select new
{
Name = p.Name,
DocumentCode = p.Document.Code
}).ToList();
dgvPersona.DataSource = list;
You may select the Id as well and keep it in a hidden column in your gridview , so that later you can use it for record updating etc.
try this:
public class Person
{
public Int32 Id { get; set; }
public String Name { get; set; }
public Document oDocument { get; set; }
}
public class Document
{
public String Type { get; set; }
public String Code { get; set; }
}
List<Person> list = new List<Person>();
dgvPersona.DataSource= list.Select(data => new { data.Name, data.oDocument.Code }).ToList();
Related
My response class
public class JSONResponse
{
public int return{ get; set; }
public string[] message{ get; set; }
public Data data{ get; set; }
}
public class Data
{
public Presence[] presences { get; set; }
}
public class Presence
{
public string id { get; set; }
public string name{ get; set; }
public Field[] fields { get; set; }
}
public class Field
{
public string label{ get; set; }
public string value { get; set; }
}
My new class
public class MyClass
{
public int Id { get; set; }
public string Name{ get; set; }
public bool Temp{ get; set; }
}
Inside the json class I have the property Fields that have a couple of value (Label, Value)
I wish to cast into MyClass and set the Temp property getting the value property based on label value of Fields :
MyClass myclass = JSONResponse.data.presences.Select(x => new MyClass()
{
Id = Convert.ToInt32(x.id),
Name = x.name,
Temp = x.fields.Where(a => a.label == "Label") // i want the value property
}).ToList();
LINQ has a set of functions to map a list to a single entry of that list. I think the most correct option in your case is SingleOrDefault.
var result = JSONResponse.data.presences.Select(x => new MyClass()
{
Id = Convert.ToInt32(x.id),
Name = x.name,
Temp = x.fields.SingleOrDefault(a => a.label == "Label")?.Value,
});
The reason I suggest SingleOrDefault over FirstOrDefault is that SingleOrDefault throws an exception when it finds multiple matches. By doing it like this you will get an Exception, not a possible incorrect value, when there are duplicate labels.
Use FirstOrDefault
Temp = x.fields.FirstOrDefault(a => a.label == "Label")?.Value
I am trying to populate the AllTerms object that will contain LegalFundClassCommercialViewModel and LegalFundClassSideLetterViewModel objects.
Basically the LEGAL_FUND_CLASS table has parent and child records and are related by column LegalParentClassId. One parent has one child. So I need to loop through legalfundClasses object and populate
IEnumerable<LegalFundClassWrapper> AllTerms . The LegalFundClassDetailsViewModel represents the records in the LEGAL_FUND_CLASS table. So legalfundClasses variable contains records from this legal_fund_class table. There are several records. Some records wont have child record. I need to populate in a way where the parent record gets added to LegalFundClassCommercialViewModel and its child record gets added to
LegalFundClassSideLetterViewModel. The wrapper would contain a collection of Parent and child records where some child records wont exist and hence the LegalFundClassSideLetterViewModel property would be null.
Can somebody give me an idea on how to go about it ?
C#
public class LegalFundClassViewModel
{
public IEnumerable<LegalFundClassWrapper> AllTerms;
public class LegalFundClassWrapper
{
public LegalFundClassDetailsViewModel LegalFundClassCommercialViewModel { get; set; }
public LegalFundClassDetailsViewModel LegalFundClassSideLetterViewModel { get; set; }
}
}
public class LegalFundClassDetailsViewModel
{
public string Description { get; set; }
public string AuditSummary { get; set; }
public string FeesReviewSummary { get; set; }
public string TermsReviewSummary { get; set; }
public int Id { get; set; }
public int FundId { get; set; }
public int FundClassType { get; set; }
public int? CurrencyId { get; set; }
public string PrimaryCurrencyName { get; set; }
public string OtherCurrencyName { get; set; }
public int? ManagerStrategyId { get; set; }
public string ManagerStrategyName { get; set; }
public int? SubVotingId { get; set; }
public string SubVotingName { get; set; }
public int? SubHotIssueId { get; set; }
public string SubHotIssueName { get; set; }
public int? RedsFrqncyId { get; set; }
public string RedsFrqncyName { get; set; }
public int? RedsNoticeDays { get; set; }
public int? NoticeTypeOfDaysId { get; set; }
public string NoticeTypeOfDaysName { get; set; }
public int? LegalParentClassId { get; set; }
}
var managerStrategyFundIds = GetService<MANAGERSTRATEGY>().WhereWithIncludes<MANAGERSTRATEGY>(x => x.ID == managerStratedyId, x => x.FUNDs).SelectMany(x => x.FUNDs).Select(x => x.ID).ToList();
var legalfundClasses = GetService<LEGAL_FUND_CLASS>().Where(x => managerStrategyFundIds.Contains(x.FUND_ID));
What I was trying creates a list of all the records in one. How do I loop through and populate the AllTerms
var allFunds = legalfundClasses.Select(fc => new LegalFundClassDetailsViewModel
{
Description = fc.DESCRIPTION,
Id = fc.ID,
FundId = fc.FUND_ID,
FundClassType = fc.CLASS_TYPE,
AuditSummary = getAuditSummary(managerStratedyId, fc.ID),
FeesReviewSummary = getFeesReviewSummary(fc),
TermsReviewSummary = getTermsReviewSummary(fc),
CurrencyId = fc.CURRENCY_ID,
});
public class LegalFundClassViewModel
{
public IEnumerable<LegalFundClassWrapper> AllTerms;
public class LegalFundClassWrapper
{
public LegalFundClassDetailsViewModel
LegalFundClassCommercialViewModel { get; set; }
public LegalFundClassDetailsViewModel
LegalFundClassSideLetterViewModel { get; set; }
}
As you can see in the image below, there are two records. The record that has value in legal_parent_class id field is the child to the record on top of it. If you notice the id of the top record matches the bottom record's legal_parent_class_id.
What is the best way to identify the child and store records in respective properties accordingly
You need left outer join. In your case
var allFunds = new[]
{
new LegalFundClassDetailsViewModel
{
Id = 101,
Description = "Parent with child"
},
new LegalFundClassDetailsViewModel
{
Id = 102,
Description = "Parent without child"
},
new LegalFundClassDetailsViewModel
{
Id = 103,
Description = "I'm child",
LegalParentClassId = 101
}
};
var allTerms = (from fund in allFunds
where fund.LegalParentClassId == null //only parents
join child in allFunds on fund.Id equals child.LegalParentClassId into gj
from child2 in gj.DefaultIfEmpty()
select new LegalFundClassViewModel.LegalFundClassWrapper { LegalFundClassCommercialViewModel = fund, LegalFundClassSideLetterViewModel = child2 })
.ToArray();
I am trying to populate my combobox with a list of companies and then get value of selected company (its Id) into my database.
I have this class CBItem:
public class CBItem
{
public string Name { get; set; }
public int Value { get; set; }
public override string ToString()
{
return Name;
}
}
I add items to combobox using this:
using (var db = new DataContext())
{
var list_of_companies = db.Companies;
foreach (Company c in list_of_companies)
{
CBItem item = new CBItem();
item.Name = c.Name;
item.Value = c.Id;
comboBox1.Items.Add(item);
}
}
Problem is when I want to get value of selected item, I have tried something like this:
new_person.Company.Id = (comboBox1.SelectedItem).Value;
Of course it doesn't work :/ Any tips?
You are right, there is something wrong with this line:
new_person.Company.Id
I don't know what is wrong. I have model Person which has foreign key to company's id.
Maybe there si something wrong with my DB model.
My Person model:
public class Person
{
public Person()
{
}
public int PersonId { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public string Job { get; set; }
public int Phone { get; set; }
public int Mobile { get; set; }
public Company Company { get; set; }
}
Company model:
public class Company
{
public Company()
{
}
public int Id { get; set; }
public string Name { get; set; }
public int NIP { get; set; }
public string Address { get; set; }
public string City { get; set; }
public int Code { get; set; }
public int Phone { get; set; }
public string Notes { get; set; }
public ICollection<Person> Person { get; set; }
}
Saving code:
using (var db = new DataContext())
{
Person new_person = new Person();
new_person.Name = textBox1.Text;
new_person.Surname = textBox2.Text;
new_person.Job = textBox3.Text;
new_person.Phone = Int32.Parse(textBox4.Text);
new_person.Mobile = Int32.Parse(textBox5.Text);
new_person.Company.Id = (comboBox1.SelectedItem as CBItem).Value;
db.Person.Add(new_person);
db.SaveChanges();
MessageBox.Show("Person successfully added!");
this.Close();
}
Your code works fine if:
new_person is not null
new_person.Company is not null
combobox.SelectedItem is not null
Also you have to cast combobox.SelectedItem to CBItem like this:
new_person.Company.Id = ((CBItem)comboBox1.SelectedItem).Value;
As a site note instead of adding each item one by one you can archive the same thing by binding the ComboBox via its DataSource property to an object that implements the IList interface or an Array:
comboBox1.DataSource = list_of_companies
.Select(c => new CBItem {
Name = c.Name,
Value = c.Id
})
.ToArray();
i have a list of objects
public int id { get; set; }
public string device_code { get; set; }
public string device_type { get; set; }
public string authentication_token { get; set; }
public string Status { get; set; }
while returning the list i want to remove "device_code" and "device_type" from the list and return the list only with "id","authentication_token" and "status".
How can I delete certain objects?
You must cast your object to another type that will contain only needed properties.
You can do this easy with linq:
var result = yourCollection.Select(x => new YourTempClass(){property1=x.property1});
You seem to not want to remove objects, but properties of the objects.
public class ClassWithAllProperties
{
public int id { get; set; }
public string device_code { get; set; }
public string device_type { get; set; }
public string authentication_token { get; set; }
public string Status { get; set; }
}
var allInstances = new List<ClassWithAllProperties>();
// populate list
var allInstancesButNotAllProperties = allInstances.Select(x => new { id = x.id, authentication_token = x.authentication_token, Status = x.Status }).ToList();
Now this list contains only the properties you want. However it obviously also does not contain instances of ClassWithAllProperties. It contains so-called anonymous classes. Classes the compiler builds in the background for you, based on your description in the new.
It's simple, create another class containing properties that are required and then return its object using the list you have created.
Original Class
public class Data {
public int id { get; set; }
public string device_code { get; set; }
public string device_type { get; set; }
public string authentication_token { get; set; }
public string Status { get; set; }
}
Class That will be returned
public class DataTobeReturned {
public int id { get; set; }
public string authentication_token { get; set; }
public string Status { get; set; }
}
Suppose you have list like
List<Data> list = // some data;
You can do
List<DataTobeReturned> list2 = list.Select(x => new DataTobeReturned { x.id, x.Status, x.authentication_token}).ToList();
Simply return the list2 object.
If you have this class:
class MyClass
{
public int id { get; set; }
public string device_code { get; set; }
public string device_type { get; set; }
public string authentication_token { get; set; }
public string Status { get; set; }
}
...and you have a list of them...
List<MyClass> list;
You can extract just the properties you want into an anonymous type by using LINQ:
var justWhatIWant = list.Select( a => new
{
id = a.id,
authentication_token = a.authentication_token,
Status = a.Status
});
The anonymous type isn't interface-compatible with anything, but you could use it to, say, create some JSON.
I have 2 classes SiteConfig, SiteConfigView. One is tightly coupled with my EF and one class to expose it to View models. Both the classes holds to a collection of type 'Brands'
I struck at writing a linq query to fetch the records from db to view model.
As I am exposing a different class to view model, I have to get the records of type 'SiteConfigView'. So I am writing a linq query but I am bit confused how to get the collection from SiteConfig to SiteConfigView.
There are my classes
public partial class SiteConfig
{
public SiteConfig()
{
this.SiteBrands = new HashSet<SiteBrand>();
}
public int IdSiteConfig { get; set; }
public string Name { get; set; }
public byte[] SiteLogo { get; set; }
public string Brands { get; set; }
public string LinkColour { get; set; }
public virtual ICollection<SiteBrand> SiteBrands { get; set; }
}
public class SiteConfigView
{
public SiteConfigView()
{
}
public int IdSiteConfig { get; set; }
public string Name { get; set; }
public byte[] SiteLogo { get; set; }
public string Brands { get; set; }
public string LinkColour { get; set; }
public IEnumerable<SiteBrandView> SiteBrands { get; set; }
}
And this is the query I am trying
var db = new SampleMVCEntities();
IQueryable<SiteConfig> test = db.SiteConfigs.Select(a => new SiteConfigView{Name = a.Name,LinkColour = a.LinkColour,SiteLogo = a.SiteLogo});
Can comebody guide me how to get the collection from SiteConfig to SiteConfigView.
Thanks
You're going on the right direction tried like this
var siteConfigs = db.SiteConfigs.AsEnumerable().Select(a => new SiteConfigView()
{
Name = a.Name,
LinkColour = a.LinkColour,
SiteLogo = a.SiteLogo,
SiteBrands = a.SiteBrands.AsEnumerable().Select(a => new SiteBrandView()
{
//Do the projection
}).ToList()
}).ToList();