Providing multiple <int> list criteria using linq in Entity Framework
I am working on a project that uses the framework entity. I want simple things, when people click the searchLookUpedit button, I want to show values ββfiltered according to the companies that exist in the Order. So here is the code:
private void SearchLookUpEdit_Customer_Click(object sender, EventArgs e) { object [] siparisNo = new object[gridView1.RowCount]; List<Siparisler> siparisList = new List<Siparisler>(); List<int> firmaIds = new List<int>(); for (int i = 0; i < gridView1.RowCount; i++) { siparisNo[i] = gridView1.GetRowCellValue(i,"SiparisNo"); int sipNo = Convert.ToInt32(siparisNo[i]); Siparisler siparis = context.Siparisler.Where(p => p.Id == sipNo).FirstOrDefault(); siparisList.Add(siparis); firmaIds.Add(siparis.Firma_Id); } for (int i = 0; i < firmaIds.Count; i++) { int a = firmaIds[i]; firmalarBindingSource.DataSource = context.Firmalar.Where(p => p.Id == ); } } Here is the second for the loop. Suppose there are 3 values ββin the list type firmaIds<int> . And suppose they are, for example, 3, 5, and 8, and I want only these 3 Companies to exist in firmalarBindingSource.DataSource after the click has finished. I tried, but it is not. If my criteria were different types of data, it was easy to filter. Is there any way to do this?
@Faby answered your question, but I just wanted to add that you can also optimize the first part of your code so that you can do everything in two lines of code more functionally using Linq :
IEnumerable<Firmalar> firmalarDataSource = Enumerable.Range(0, gridView1.RowCount - 1) .Select((index) => { var siparisId = Convert.ToInt32(gridView1.GetRowCellValue(index, "SiparisNo")); var siparis = context.Siparisler.FirstOrDefault(p => p.Id == siparisId); return context.Firmalar.FirstOrDefault(f => f.Id == siparis.Firma_Id); }) .Distinct(); firmalarBindingSource.DataSource = firmalarDataSource; Note : these are two lines, but I adjusted the formatting to be more readable;)
If you evaluate performance by lines of code, here is an example of three lines with fewer database calls:
var siparisIds = Enumerable.Range(0, gridView1.RowCount - 1) .Select(index => Convert.ToInt32(gridView1.GetRowCellValue(index, "SiparisNo"))); var firmaIds = context.Siparisler.Where(p => siparisIds.Contains(p.Id)).Select(s => s.Firma_Id).Distinct(); firmalarBindingSource.DataSource = context.Firmalar.Where(f => firmaIds.Contains(f.Id));