So, I'm using Syncfusion controls and I've a MultipleSelectionCombobox where user can filter multiple arguments.
I have a query which will load a list based on parameters query.
So, first, I have a class to hold my values;
public class Orders
{
public int ID { get; set; }
public string OrderNum { get; set; }
public string Status { get; set; }
public DateTime Date { get; set; }
}
Then, the query:
public IEnumerable<Orders> LoadData()
{
var ctx = new DbContext();
var query = (from o in ctx.tblOrders.AsQueryable()
select new Orders
{
ID = o.OrderID,
OrderNum = o.OrderNum.ToString(),
Status = o.OrderStatus,
Date = o.OrderDate
});
if(CmbOrderStatus.SelectedItems != null)
{
List<string> list = new List<string>();
foreach (SelectedItems obj in CmbOrderStatus.SelectedItems)
{
list.Add(obj.ToString());
}
for(int i = 0; i < list.Count; i++)
{
var value = list[i];
query = query.Where(p => p.Status == value);
}
}
return query.ToList();
}
So, in Database in have many Orders and many OrderStatus, like "Opened", "Delayed", "Closed".
So, if I filter in CmbOrderStatus "Opened" and "Delayed", I get nothing! If only one is selected, I get nothing!
Any help here?
Thanks
The code use only last filter.
Try this:
public IEnumerable<Orders> LoadData()
{
var ctx = new DbContext();
var query = (from o in ctx.tblOrders.AsQueryable()
select new Orders
{
ID = o.OrderID,
OrderNum = o.OrderNum.ToString(),
Status = o.OrderStatus,
Date = o.OrderDate
});
if(CmbOrderStatus.SelectedItems != null)
{
List<string> list = new List<string>();
foreach (SelectedItems obj in CmbOrderStatus.SelectedItems)
{
list.Add(obj.ToString());
}
query = query.Where(p => list.Contains(p.Status));
}
return query.ToList();
}
Related
using the lambda expression I just want to select 2 columns but it throws error.
Code:
public List<Certificates> GetClientsList(string certificationNo = "")
{
List<Certificates> certificatesList = new List<Certificates>();
var query = uow.CertificatesRepository.GetQueryable().AsQueryable();
if (!string.IsNullOrEmpty(certificationNo))
{
query = query.Where(x => x.CertificationNo.Contains(certificationNo)).Select(n => new { ClientName= n.Client, ID= n.CertificatesID});
}
certificatesList = query.ToList();
return certificatesList;
}
Certificates class:
public class Certificates
{
public int CertificatesID { get; set; }
public string FileName { get; set; }
[Required]
[Display(Name = "Certification No")]
public string CertificationNo { get; set; }
[Required]
[Display(Name = "Issue Date")]
public string IssueDate { get; set; }
[Required]
public string Details { get; set; }
[Required]
public string Client { get; set; }
}
Error:
Cannot convert Anonymous querable type to List
Why do you need it converted to Queryable first? what type does uow.CertificatesRepository.GetQueryable() return?
public List<Certificates> GetClientsList(string certificationNo = "")
{
var query = uow.CertificatesRepository.GetQueryable(); // do ToList here if it is IQuerable, but as it seems it was not.
return query.Where(x=>x.CertificationNo.Contains(certificationNo)).Select(x=> new Certificates(){ClientName= n.Client, ID= n.CertificatesID}).ToList();
}
You are probably looking for something like this (depending on the return type of CertificatesRepository)
public List<Certificates> GetClientsList(string certificationNo = "")
{
var query = uow.CertificatesRepository;
if (string.IsNullOrEmpty(certificationNo))
return query.ToList();
return query.Where(x => x.CertificationNo.Contains(certificationNo))
.ToList();
}
Update
The thing is want is to select 2 columns only
public List<Certificates> GetClientsList(string certificationNo = "")
{
var query = uow.CertificatesRepository;
if (string.IsNullOrEmpty(certificationNo))
return query.Select(n => new Certificates { ClientName = n.Client, ID = n.CertificatesID})
.ToList();
return query.Where(x => x.CertificationNo.Contains(certificationNo))
.Select(n => new Certificates { ClientName = n.Client, ID = n.CertificatesID})
.ToList();
}
or
public List<(int ID , string ClientName)> GetClientsList(string certificationNo = "")
{
var query = uow.CertificatesRepository;
if (string.IsNullOrEmpty(certificationNo))
return query.Select(n => (ID = n.CertificatesID, ClientName = n.Client))
.ToList();
return query.Where(x => x.CertificationNo.Contains(certificationNo))
.Select(n => (ID = n.CertificatesID, ClientName = n.Client))
.ToList();
}
Your Select returns anonymous objects. These anonymous objects of course can't be converted to Certificates.
If you really want to use your Certificates class, then you could just create new objects in your select:
public List<Certificates> GetClientsList(string certificationNo = "")
{
List<Certificates> certificatesList = new List<Certificates>();
var query = uow.CertificatesRepository.GetQueryable().AsQueryable();
if (!string.IsNullOrEmpty(certificationNo))
{
query = query.Where(x => x.CertificationNo.Contains(certificationNo)).Select(n => new Certificates{ Client = n.Client, CertificatesID = n.CertificatesID});
}
certificatesList = query.ToList();
return certificatesList;
}
A better solution would probably be to create a new class which only contains the two required properties.
A third possibility is to return a List<dynamic> instead. But then you are not strongly typed anymore.
I am running into this error
cannot convert from 'System.Collections.Generic.List' to 'HWC.DataAccess.FAREmailList' HWC.DataAccess
I am not understanding this error because its the same list type
here is the method that I am using
public void PrepareToSendEmailFromFAR(int id)
{
HWC = new HWCEntities();
FileAReport far = HWC.FileAReports.Where(w => w.FileAReportID == id).FirstOrDefault();
List<FAREmailList> emailList = null;
if(far.DistrictID != 0)
{
emailList = new List<FAREmailList>();
var query = from dcx in HWC.DistrictContactXREFs
where
dcx.DistrictID == far.DistrictID
select new
{
dcx.ContactID,
dcx.Contact.ContactEmail,
dcx.Contact.ContactName
};
foreach(var a in query)
{
emailList.Add(new FAREmailList
{
ContactName = a.ContactName,
EmailAddress = a.ContactEmail
});
}
SendEmailFromFAR(emailList);
}
if(far.DistrictID == 0)
{
emailList = new List<FAREmailList>();
var query = from dcx in HWC.DistrictContactXREFs
join d in HWC.Districts on dcx.DistrictID equals d.DistrictID into d_join
from d in d_join.DefaultIfEmpty()
join sp in HWC.StateProvinces on new { StateProvinceID = d.StateID } equals new { StateProvinceID = sp.StateProvinceID }
where
d.StateID == far.StateCountyID
select new
{
dcx.ContactID,
dcx.Contact.ContactEmail,
dcx.Contact.ContactName
};
foreach (var a in query)
{
emailList.Add(new FAREmailList
{
ContactName = a.ContactName,
EmailAddress = a.ContactEmail
});
}
SendEmailFromFAR(emailList);
}
}
and here is the method thats receiving the emailList
public void SendEmailFromFAR(FAREmailList el)
{
}
the data class is
public class FAREmailList
{
public string ContactName { get; set; }
public string EmailAddress { get; set; }
}
the error is being thrown at
SendEmailFromFAR(emailList);
I am not seeing what the issue is, is it because this is all in the same class file?
The error makes sense to me. emailList is of type List<FAREmailList> and SendEmailFromFAR takes a FAREmailList as input.
I'am learning c# and angular and I try to aggregate the data of a product with the follower. I have some NotMapped-fields in my class (codefirst)
[NotMapped]
public string followitemtitle { get; set; }
[NotMapped]
public string followitemprice { get; set; }
And I get 2 items of each group
return _context.Product
.Include(c => c.productgroup)
.GroupBy(p => p.productgroupid)
.SelectMany(g => g.OrderByDescending(p => p.productdate).Take(2));
What I try is a loop and build a new return-value -> only the first product ( every second in the list) - with some information of the follower product.
[HttpGet("new")]
public IActionResult GetProductsIncFollower()
{
var productEntities = _productrepository.GetProductsIncFollower();
Product tmpData = new Product();
IEnumerable<Product> tmpDataList = new List<Product>();
int index = 1;
string tmpFollowtitle = "";
string tmpFollowprice = "";
foreach (var item in productEntities)
{
if(index % 2 != 0)
{
tmpFollowtitle = item.title;
tmpFollowprice = item.price;
}
else
{
tmpData = item;
tmpData.followitemtitle = tmpFollowtitle;
tmpData.followitemprice = tmpFollowprice;
tmpDataList.Append(tmpData);
}
index++;
}
var results = tmpDataList;
return Ok(results);
}
But tmpDataList is empty and I dont understand why.
I have done the below which is working fine.
public StandardReportsModel GetStandardReportsModel(string adUser, string adPassword, IPrincipal user)
{
var myItems = getMyItems().Where(myItem => !string.IsNullOrEmpty(myItem.Description));
var categories = new List<string>();
var myItems = new List<MyModel>();
foreach (var myItem in myItems)
{
var myIndex = myItem.Description.IndexOf('*');
var category = myIndex != -1 ? myItem.Description.Substring(0, myIndex).ToUpper() : myItem.Description.ToUpper();
if (categories.IndexOf(category) == -1)
{
categories.Add(category);
}
myItems.Add(getMyItem(myItem, category));
}
categories.Sort();
return new StandardModel { Categories = categories, MyItems = myItems };
}
private MyModel getMyItem(MyItem myItem, string category)
{
var categoryIdentifierIndex = myItem.Description.LastIndexOf(Delimiters.CategoryDescriptionDelimiter);
var description = categoryIdentifierIndex != -1 ? myItem.Description.Substring(categoryIdentifierIndex + 1, (myItem.Description.Length - categoryIdentifierIndex + 1))) : myItem.Description;
return new MyModel{ Name = myItem.Name, Description = myItem.Description, Category = category };
}
public class StandardModel
{
public List<string> Categories { get; set; }
public List<MyModel> MyItems { get; set; }
}
Now I am trying to do the same with Linq and I have reached till below. From the obtained result I can get distinct of category and sort it. Is there a way by which it can be doen in a single query?
var result = myItems.Where(myItem => !string.IsNullOrEmpty(myItem.Description))
.Select(ci => new MyModel
{
Name = ci.Name,
Category = ci.Description.Split('*')[0],
Description = ci.Description.Split('*')[2]
}).ToList();
I want categories and their items. Probably I might have to use group by here.
Please suggest
Dictionary<string, List<MyModel>> result = myItems
.Where(myItem => !string.IsNullOrEmpty(myItem.Description))
.Select(ci => new MyModel
{
Name = ci.Name,
Category = ci.Description.Split('*')[0],
Description = ci.Description.Split('*')[2]
})
.GroupBy(e => e.Category)
.ToDictionary(e => e.Key, e => e.ToList());
Looking for an example where I can filter my collection based on some filtering criteria.
I have been looking for some example where given a list /array i can filter a collection.
In the example below in my find method I am trying to filter based on 2 values ,looking for something like an "IN" function any suggestions?
class Program
{
static void Main()
{
//Print all customres that belong to below deparments and match on surname
var criteria=new Criteria
{
Departments = new List<string> {"BusinessAnalyst", "Account"},
Surname = "Bloggs"
};
List<Customer> customers = Repository.Find(criteria);
customers.ForEach(x => Console.WriteLine(string.Format("Surname: {0} Department :{1}", x.Surname,x.Department)));
Console.Read();
}
}
public class Repository
{
public static List<Customer>GetCustomers()
{
return new List<Customer>
{
new Customer { Name = "Jon",Surname="Smith",Department = DepartmentType.Managers},
new Customer{Name = "Bill",Surname = "Gates",Department = DepartmentType.Managers},
new Customer { Name = "Mary",Surname = "Bug",Department = DepartmentType.Developers},
new Customer { Name = "Mark",Surname="Boo",Department = DepartmentType.Account},
new Customer{Name = "Ron",Surname = "Scott",Department = DepartmentType.Managers},
new Customer { Name = "Jonny",Surname = "Dip",Department = DepartmentType.Developers},
new Customer { Name = "Mary",Surname = "Bloggs",Department = DepartmentType.BusinessAnalyst},
new Customer { Name = "Mary",Surname = "Bug",Department = DepartmentType.Account},
new Customer { Name = "Jonny",Surname = "Dip",Department = DepartmentType.Account},
new Customer { Name = "Mary",Surname = "Bloggs",Department = DepartmentType.Managers}
};
}
public static List<Customer> Find(Criteria criteria)
{
List<Customer>customers=Repository.GetCustomers();
//Filter on departments
//ERROR HERE AS I cannot do this "IN" would be fantastic.
customers = customers.Contains(criteria.Departments);
//now filter on name
customers = customers.Where(x => x.Surname == criteria.Surname).ToList();
return customers;
}
}
public enum DepartmentType
{
Account,
Managers,
Developers,
BusinessAnalyst
}
public class Customer
{
public string Name { get; set; }
public string Surname { get; set; }
public DepartmentType Department { get; set; }
}
public class Criteria
{
public Criteria()
{
Departments=new List<string>();
}
public string Name { get; set; }
public string Surname { get; set; }
public List<string> Departments { get; set; }
}
public static List<Customer> Find(Criteria criteria)
{
List<Customer> customers = Repository.GetCustomers();
var customers2 = customers.Where(x => criteria.Departments.Contains(x.Department.ToString()));
var customers3 = customers2.Where(x => x.Surname == criteria.Surname);
return customers3.ToList();
}
But considering you use an enum for the Department (DepartmentType), shouldn't your Criteria class use the same instead of a string?
If you define the criteria.Departments as List<DepartmentType> then you can write
public static List<Customer> Find(Criteria criteria)
{
List<Customer> customers = Repository.GetCustomers();
var customers2 = customers.Where(x => criteria.Departments.Contains(x.Department));
var customers3 = customers2.Where(x => x.Surname == criteria.Surname);
return customers3.ToList();
}
Contains returns a bool defining whether a specified object is contained in a collection. Based on your example, you will need to use Where to filter the customers, then use Contains on the departments:
customers = customers.Where(c => criteria.Departments.Contains(c.Department));
i think you want something like this..
customers = customers.Where(c => criteria.Departments.Contains(c.Department));
You want
Customers.Where(c => criteria.Departments.Contains(c.Department.ToString()))
Not sure if this is what you're looking for but the following:
List<Customer> FilteredCustomers = (from c in customers where Criteria.Departments.Contains(c.deparment) && c.surname == Criteria.Surname select c).ToList();
Would equate to something like this in SQL:
SELECT *
FROM Customers
WHERE Department IN (
List of departments
)
AND Surname = surname
I haven't tested this but I think it should work and bring back what you want.