I want to order by pincode with string empty, when I am trying to convert pincode to an integer for sorting, I am getting an error.
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public string City { get; set; }
public string Pincode { get; set; }
}
List<Student> objStudentList = new List<Student>();
objStudentList.Add(new Student() { Id = 1, Name = "gopi", City="Chennai", Pincode = "600002" });
objStudentList.Add(new Student() { Id = 2, Name = "ravi", City = "Bangulor", Pincode = "600 001" });
objStudentList.Add(new Student() { Id = 3, Name = "mani", City = "Madurai", Pincode = "600 007" });
objStudentList.Add(new Student() { Id = 4, Name = "anbu", City = "Thiruchi", Pincode = "600 005" });
objStudentList.Add(new Student() { Id = 4, Name = "kumar", City = "Thiruchi", Pincode = "" });
objStudentList = objStudentList.OrderBy(a => int.Parse(Regex.Replace(a.Pincode.Replace(" ", "").Replace("\t", ""), #"\t|\n|\r", ""))).ToList();
can anyone tell me what the problem at hand is and how to fix it?
you can avoid empty strings by first filtering them out. i.e.
objStudentList = objStudentList.Where(a => !string.IsNullOrEmpty(a.Pincode))
.OrderBy(a => int.Parse(a.Pincode)).ToList();
However, if you want to keep the Student objects that have an empty string but rather replace their Pincode property with "0" you can try this:
objStudentList = objStudentList.OrderBy(a => string.IsNullOrEmpty(a.Pincode) ? int.Parse("0") : int.Parse(a.Pincode))
.ToList();
The reason is that you're trying to covert an empty string to int. If you want to get 0 as a result, you must replace "" to "0"
Related
I'm trying to take a list of doctor with locations. each row contains doctor information along with a location. Doctor "A" might have 3 locations so doctor "A" would have 3 rows. I would like to somehow group using linq to take this list to create a new doctor class with a List.
Here is my initial list. Each row duplicates ProviderId and Name if the provider has more than one location
var providerLocation = new List<ProviderLocation>
{
new ProviderLocation
{
ProviderId = "1",
FirstName = "Provider1",
AddressId = "1",
City = "Des Moines"
},
new ProviderLocation
{
ProviderId = "1",
FirstName = "Provider1",
AddressId = "2",
City = "Urbandale"
},
new ProviderLocation
{
ProviderId = "2",
FirstName = "Provider2",
AddressId = "3",
City = "Dallas"
},
new ProviderLocation
{
ProviderId = "2",
FirstName = "Provider2",
AddressId = "4",
City = "Fort Worth"
}
};
would like it to go into new classs that looks like:
public class Doctor
{
public string ProviderId { get; set; }
public string FirstName { get; set; }
public List<DoctorLocation> Locations { get; set; }
}
public class DoctorLocation
{
public string AddressId { get; set; }
public string City { get; set; }
}
Then I could reference my doctor list by:
var doctorList = List<Doctor>
Is there a way to make this happen using linq without having to loop through the list to manually populate the new classes?
Does this produce your desired result ?
var doctorList = providerLocation
.GroupBy(pl => new { pl.ProviderId, pl.FirstName })
.Select(group => new Doctor()
{
ProviderId = group.Key.ProviderId,
FirstName = group.Key.FirstName,
Locations = group.Select(dl => new DoctorLocation()
{
AddressId = dl.AddressId,
City = dl.City
}).ToList()
})
.ToList();
Result:
This LINQ GroupBy your ProviderLocation, returning a list of IGrouping with key being an anonymous object of ProviderId and FirstName.
We get a Doctor for every IGrouping ( taken from group.Key properties )
Then we do a Select on this IGrouping, returning a DoctorLocation for every Item this IGrouping contains.
You can use the ConvertAll method. This is one way to do it -
public static List<Doctor> MakeDoctorsListFrom(List<ProviderLocation> providerLocations)
{
return providerLocations.ConvertAll<Doctor>((input) => new Doctor()
{
ProviderId = input.ProviderId,
FirstName = input.FirstName,
Locations = new List<DoctorLocation>(){
new DoctorLocation(){
AddressId = input.AddressId,
City = input.City
}
}
});
}
And you call it from your code -
var doctors = MakeDoctorsCollectionFrom(providerLocation);
I have three different lists including students, courses, and grades. What I want to do is to use some of courses and students properties in grades variable. Here is my code:
namespace educationsystem
{
public class student
{
public int scode { get; set; }
public string name { get;set;}
public string lastname {get;set;}
public long phone {get;set;}
}
public class course
{
public int code { get; set;}
public string name { set; get;}
public int unit { set; get;}
}
public class grade
{
public student studentinfo { get; set; }
public course courseinfo { get; set; }
public double value { get; set; }
public int term { get; set; }
}
public class education
{
}
class Program
{
static void Main(string[] args)
{
List<student> Students = new List<student>();
List<course> courses = new List<course>();
List<int> grades = new List<int>();
Students.Add(new student { scode=1,name = "mahta", lastname = "sahabi", phone = 3244 });
Students.Add(new student { scode=2, name = "niki", lastname = "fard", phone = 5411 });
Students.Add(new student { scode=3, name = "hana", lastname = "alipoor", phone = 6121 });
courses.Add(new course { code = 1, name = "Mathemathics", unit = 3 });
courses.Add(new course { code = 2, name = "physics", unit = 3 });
courses.Add(new course { code = 3, name = "computer", unit = 3 });
Students.ForEach((student) => { Console.WriteLine(student.scode+" "+student.name + " " + student.lastname + " " + student.phone); });
courses.ForEach((course) => { Console.WriteLine(course.code + " " + course.name + " " + course.unit); });
Console.ReadKey();
}
I would like to print the grades like:
mahta sahabi mathematics 20.
How can I do such thing?
To hardcode a grade and print it, you can use:
List<grade> grades = new List<grade>(); // instead of List<int>
// ...
grades.Add(new grade
{
studentinfo = Students.Where(s => s.scode == 1).First(),
courseinfo = courses.Where(c => c.code == 1).First(),
value = 20.0d,
term = 1
});
// ...
grades.ForEach((grade) => { Console.WriteLine(grade.studentinfo.name + " " + grade.studentinfo.lastname + " " + grade.courseinfo.name + " " + grade.value); });
Is that what you were looking for?
You'll need to associate the appropriate students and courses when you create the grades collection. You'll then be able to access the assocation by navigating it
grade.studentinfo.name
and
grade.courseinfo.name
Since there will likely be a many : many relationship between students and courses, how about initializing your objects through a Dictionary, to allow easy identification of each student and course when you define the associations to grade:
var students = new []
{
new student { scode=1,name = "mahta", lastname = "sahabi", phone = 3244 },
new student { scode=2, name = "niki", lastname = "fard", phone = 5411 },
... etc
}.ToDictionary(s => s.scode);
var courses = new []
{
new course { code = 1, name = "Mathemathics", unit = 3 },
....
}.ToDictionary(c => c.code);
var grades = new []
{
new grade { term = 1, value = 53, student = students[1], course = courses[2] },
new grade { term = 2, value = 99, student = students[1], course = courses[1] },
...
}
You'll then be able to print these out like so:
foreach(var grade in grades)
{
Console.WriteLine($"{grade.studentinfo.name} {grade.courseinfo.name} {grade.value}" );
}
I have make one list str.
List<string> str = new List<string>();
str.AddRange(new string[] { "ahmedabad", "surat", "vadodara", "rajkot", "bhavnagar", "jamnagar", "gandhidham", "gandhinagar" });
I have create one class
class MatchAddress
{
public string Name { get; set; }
public string Taluka { get; set; }
public string District { get; set; }
public string Pincode { get; set; }
public float Rank { get; set; }
}
List<MatchAddress> lm;
List<MatchAddress> lmmatch.
fill the lm list.
lm.Add(new MatchAddress() { District = "vadodara", Taluka = "vadodara", Rank = 1f, Name = "vadodara" });
lm.Add(new MatchAddress() { District = "gandhinagar", Taluka = "gandhinagar", Rank = 1f, Name = "vadodara" });
foreach (MatchAddress ma in lm)
{
string pincode ="";
// what logic i write in below then only we got the vadodara because that name are in both taluka and name then only set nulll if any one differ then not set null.
if (str.Contains(ma.Name) && str.Contains(ma.Taluka.ToLower()))
{
pincode = null;
}
lmmatch.Add(new MatchAddress() { Name = ma.Name, District = ma.District, Pincode = (pincode == null)? null : ma.Pincode , Rank = rank, Taluka = ma.Taluka });
}
so in this lmmatch list for both the MatchAddress object set pincode null but i wan't null for vadodara only and that have same taluka and village name.
if the taluka and name are different then not set pincode null.
reason behind this is where in lm list where pincode and taluka both have vadodara then only set the pincode null .
but this code that i have write also set pincode null for name vadodara where taluka not same they have gandhinagar.
so after rus this code i have got two object and they both have set pincode null but i wan't to only for vadodara where they have both name and taluka same.
so any idea how i can solve this problem ?
You Need to change only in your code
if (str.Contains(ma.Name) && ma.Name.Equals(ma.Taluka))
You Just Need to comare ma.Name = ma.taluka simple
Change your if as below
if (str.Contains(ma.Name) && ma.Name.ToLower().Equals(ma.Taluka.ToLower()))
I want to swap the list as explained below. I want to retain the count of list with some element values(not all) to be swapped from 'primary' to 'secondary'.
namespace listswap
{
public class emp
{
public int id { get; set; }
public string primary { get; set; }
public string fName { get; set; }
public string lName { get; set; }
public string state { get; set; }
public string country { get; set; }
}
class Program
{
static void Main(string[] args)
{
var empList = new List<emp>();
empList.AddRange(new emp[] { new emp {primary = "Yes", id = 1, fName = "Vivek", lName = "Ranjan", state = "TN", country = "India"},
new emp { primary = "No", id = 2, fName = "Deepak", lName = "Kumar", state = "AP", country = "UK"},
});
/* Desired list :
No of list 1 with two elements
empList[0]. primary = "Yes", id = 1, fName = "Vivek", lName = "Ranjan", state = "TN", country = "India"
empList[1]. primary = "No", id = 2, fName = "Vivek", lName = "Ranjan", state = "TN", country = "India"
*/
}
}
}
This is basics and as simple as:
var l1 = empList.Where(c=>c.primary == "Yes").ToList();
var l2 = empList.Where(c=>c.primary == "No").ToList();
For list of lists:
var result = empList.GroupBy(c => c.primary).Select(c => c.ToList()).ToList();
EDIT:
var primary = empList.FirstOrDefault(c => c.primary == "Yes");
var r = empList.Select(c => new emp
{
primary = c.primary,
id = c.id,
fName = primary != null ? primary.fName : c.fName,
lName = primary != null ? primary.lName : c.lName,
state = primary != null ? primary.state : c.state,
country = primary != null ? primary.country : c.country
}).ToList();
From the picture above you can see my program. The problem i have is that my combobox for Countries on the bottom does show up on my listview. I dont know why, has it to do with that Countries is not a string? and whats the solution. I have been trying for a very long time with this, i need all help there is for you guys to help. Thanks in advance
Form 1 = listview
Form 2 = my customer manager (the picture above)
down here is inside Form1
public partial class MainForm : Form
{
CustomerFiles.Contact contact = new CustomerFiles.Contact();
CustomerFiles.Address address = new CustomerFiles.Address();
CustomerFrame customerframe = new CustomerFrame();
private void MainForm_Load(object sender, EventArgs e)
{
if (customerframe.ShowDialog() == DialogResult.OK) //if button OK is clicked then value will be inserted
{
// var item = string.Format("[{0}]",contact.ToString());
listView1.Items.Add(string.Format("[{0}]", customerframe.ToString()));
}
}
Down here is inside Form2
public partial class CustomerFrame : Form
{
CustomerFiles.Address address = new CustomerFiles.Address();
CustomerFiles.Contact contact = new CustomerFiles.Contact();
CustomerFiles.Countries country = new CustomerFiles.Countries();
public string firstName { get; set; }
public string lastName { get; set; }
internal CustomerFiles.Phone phone { get; set; }
internal CustomerFiles.Email email { get; set; }
internal CustomerFiles.Address addressinfo { get; set; }
public string city { get; set; }
internal CustomerFiles.Countries countryinfo { get; set; }
public string street { get; set; }
public string zipcode { get; set; }
public CustomerFrame()
{
InitializeComponent();
List<CustomerFiles.Countries> countries = new List<CustomerFiles.Countries> {
new CustomerFiles.Countries{ CountryId = 1, Name = "Bulgaria"},
new CustomerFiles.Countries{ CountryId = 2, Name = "France"},
new CustomerFiles.Countries{ CountryId = 3, Name = "Brazil"},
new CustomerFiles.Countries{ CountryId = 4, Name = "Russia"},
new CustomerFiles.Countries{ CountryId = 5, Name = "South Africa"},
new CustomerFiles.Countries{ CountryId = 6, Name = "Kurdistan"},
new CustomerFiles.Countries{ CountryId = 7, Name = "China"},
new CustomerFiles.Countries{ CountryId = 8, Name = "Japan"},
new CustomerFiles.Countries{ CountryId = 9, Name = "United States of America"},
new CustomerFiles.Countries{ CountryId = 10, Name = "UK"},
new CustomerFiles.Countries{ CountryId = 11, Name = "Australia"},
new CustomerFiles.Countries{ CountryId = 12, Name = "Germany"},
new CustomerFiles.Countries{ CountryId = 13, Name = "Sweden"},};
cbCountry.DataSource = countries;
cbCountry.DisplayMember = "Name";
cbCountry.ValueMember = "CountryId";
cbCountry.SelectedValue = 1;
btnOk.DialogResult = DialogResult.OK;
contact.ToString();
address.ToString();
}
private void btnOk_Click(object sender, EventArgs e)
{
// inside contact
contact.FirstName = tbFirstName.Text;
firstName = contact.FirstName;
contact.LastName = tbLastName.Text;
lastName = contact.LastName;
contact.PhoneData = new CustomerFiles.Phone(tbCellPhone.Text);
phone = contact.PhoneData;
contact.PhoneData = new CustomerFiles.Phone(tbHomePhone.Text);
email = contact.EmailData;
//inside address class
address.City = tbCity.Text;
city = address.City;
address.Country = new CustomerFiles.Countries(cbCountry.Text);
countryinfo = address.Country;
address.Street = tbStreet.Text;
street = address.Street;
address.ZipCode = tbZipCode.Text;
zipcode = address.ZipCode;
}
public override string ToString()
{
return string.Format("[{0}, {1}]", contact.ToString(), address.ToString());
}
And down here is inside my address class
class Address
{
private string city;
public Countries country;
private string street;
private string strErrMessage;
private string zipCode;
public Address()
{
string strErrMessage = string.Empty;
string street = string.Empty;
string zipCode = string.Empty;
string city = string.Empty;
}
public Address(string street, string zipCode, string city)
{
Street = street;
ZipCode = zipCode;
City = city;
}
public Address(string street, string zipCode, string city, Countries country)
{
Street = street;
ZipCode = zipCode;
City = city;
Country = country;
strErrMessage = string.Empty;
}
public Countries Country
{
get
{
return country;
}
set
{
country = value;
}
}
public override string ToString()
{
return string.Format("[{0}, {1}, {2}, {3}]", city, zipCode, street, country);
}
}
It looks like you are adding the Text property from the form:
listView1.Items.Add(string.Format("[{0}]", customerframe.ToString()));
Change that to use the value you want to use. It's not very clear what you want to display in the ListView.
Maybe it's as simple as:
listView1.Items.Add(cbCountry.SelectedItem);
Check for null, etc.
Make sure your Country class overrides the ToString() function like you have in your other classes.