Converting a summed sql query to LINQ - linq-to-sql

I have the following SQL code from a legacy application that I have been given to work on:
SELECT [timePeriodLabel]
,[tariffCost]
,[totalUnits]
,[totalMoneyValue]
into #allRates
FROM [halfHourlyCustomers3NF].[dbo].[halfHourlyBillsTariffTotals]
where invoiceNumber = #invoiceNumber
select 'eveningAndWeekend' as timePeriodLabel,
tariffcost,
sum(totalUnits) as totalUnits,
sum(totalMoneyValue) as totalMoneyValue
into #newCollection
from #allRates
where timePeriodLabel = 'evening' or
timePeriodLabel = 'weekend'
group by tariffcost
insert into #newCollection
select 'winterDay' as timePeriodLabel,
tariffcost,
sum(totalUnits) as totalUnits,
sum(totalMoneyValue) as totalMoneyValue
from #allRates
where timePeriodLabel = 'winterDayBeforePeak' or
timePeriodLabel = 'winterDayAfterPeak'
group by tariffcost
insert into #newCollection
select 'night' as timePeriodLabel,
tariffcost as tariffCost,
sum(totalUnits) as totalUnits,
sum(totalMoneyValue) as totalMoneyValue
from #allRates
where timePeriodLabel = 'nightWeekday' or
timePeriodLabel = 'morningWeekday' or
timePeriodLabel = 'nightWeekend' or
timePeriodLabel = 'morningWeekend'
group by tariffcost
insert into #newCollection
select *
from #allRates
where not(timePeriodLabel = 'winterDayBeforePeak' or
timePeriodLabel = 'winterDayAfterPeak' or
timePeriodLabel = 'nightWeekday' or
timePeriodLabel = 'morningWeekday' or
timePeriodLabel = 'nightWeekend' or
timePeriodLabel = 'morningWeekend'or
timePeriodLabel = 'evening' or
timePeriodLabel = 'weekend')
select *
from #newCollection
This helps to filter and sum data from a table as follows:
winterDayBeforePeak 12.0000 926.5850 111.1900
winterDayAfterPeak 12.0000 151.7650 18.2100
winterPeak 13.0000 331.5100 43.1000
evening 6.0000 172.9250 10.3800
weekend 6.0000 616.5350 36.9900
nightWeekday 8.0000 1362.5150 109.0000
morningWeekday 8.0000 3627.2750 290.1800
nightWeekend 8.0000 533.8800 42.7100
morningWeekend 8.0000 1439.3100 115.1400
I have created an Entity framework application with a List variable called TariffTotals and I want to add the results of the query transformation into another List variable called SummerTariffTotals
I have looked on MDSN for the documentation to do this and I came across this article:[EF Summing Link][1]
Having looked at some answers on Stack Overflow I have tried the following:
var test = db.TariffCaclulations.GroupBy(row => new { row.TariffCost })
.Select(g => new HalfHourlyBillTariffCalculation()
{
TimePeriodLabel = "eveningAndWeekend",
TariffCost = g.Key.TariffCost,
TotalUnits = g.Sum(x => x.TotalUnits),
TotalMoneyValue = g.Sum(x => x.TotalMoneyValue)
})
.ToList();
Once I have the variable I was then going to add it to the summed table but I am getting an error The entity or complex type 'Project.Models.HalfHourlyBillTariffCalculation' cannot be constructed in a LINQ to Entities query."}
Any pointers on how I can overcome this?

The error tells you that you can't create complex type. That means you can't create new Entity object from your linq query. You should create POCO object and everything should be fine:
Your POCO class:
public class HalfHourlyBillTariffCalculationPOCO
{
public string TimePeriodLabel { get; set; }
public decimal TariffCost { get; set; }
public decimal TotalUnits { get; set; }
public decimal TotalMoneyValue { get; set; }
}
Then your cal use it easily:
var test = db.TariffCaclulations.GroupBy(row => new { row.TariffCost })
.Select(g => new HalfHourlyBillTariffCalculationPOCO()
{
TimePeriodLabel = "eveningAndWeekend",
TariffCost = g.Key.TariffCost,
TotalUnits = g.Sum(x => x.TotalUnits),
TotalMoneyValue = g.Sum(x => x.TotalMoneyValue)
})
.ToList();

Related

.net core connect to mysql server

I have a issue here for the connect mysql.
I have a vps that contain mysql server have a database name is 'tuyendungbg'. it's had table and data in there. But when i'm connect and query to select data, that have error for 'Table 'tuyendungbg.Careers' doesn't exist'.
here is my controller :
[HttpGet("/nganh-nghe/{slug?}")]
public IActionResult Index(string slug, [FromQuery(Name =
"p")] int currentPage, int
pageSize)
{
if (!string.IsNullOrEmpty(slug))
{
var career = _context.Careers.FirstOrDefault(x =>
x.Slug.Equals(slug));
if (career != null)
{
ViewBag.CareerName = career.CareerName;
//var qr = _context.Careers.ToList();
var qr = (from p in
_context.CompanyCareers.Where(x => x.CareerId ==
career.ID)
from b in _context.Companies.Where(x =>
x.Id == p.CompanyId)
from i in
_context.IndustrialAreas.Where(x => x.ID ==
b.IndustrialAreaId).DefaultIfEmpty()
select new CompanyModelView()
{
Id = b.Id,
CompanyName = b.CompanyName,
BasicSalary = b.BasicSalary,
Allowance = b.Allowance,
DateCreate = b.DateCreate,
JobTitle = b.JobTitle,
Src = b.Src,
_IndustrialArea = i,
Address = b.Address,
Slug = b.Slug,
WorkTypes = (from tc in
_context.CompanyWorkTypes.Where(x =>
x.CompanyId == b.Id)
from type in
_context.WorkTypes.Where(x => x.Id
==
tc.TypeId)
select type)
}
).OrderByDescending(x => x.DateCreate).ToList();
// var worktype = (from w in
_context.CompanyWorkTypes.Where(x =>
x.CompanyId
== qr.))
var totalCate = qr.Count();
if (pageSize <= 0) pageSize = 10;
int countPages =
(int)Math.Ceiling((double)totalCate / pageSize);
if (currentPage > countPages)
currentPage = countPages;
if (currentPage < 1)
currentPage = 1;
var pagingModel = new PagingModel()
{
countpages = countPages,
currentpage = currentPage,
generateUrl = (pageNumber) =>
Url.Action(nameof(Index), new
{
p = pageNumber,
pageSize = pageSize
})
};
ViewBag.pagingModel = pagingModel;
ViewBag.totalPost = totalCate;
ViewBag.cateIndex = (currentPage - 1) * pageSize;
var companies = qr.Skip((currentPage - 1) *
pageSize)
.Take(pageSize).ToList();
ViewBag.JobCount = companies.Count();
//Set slider menu
var leftSlider = new LeftSliderModel()
{
Areas = new SelectList(_context.Areas,
nameof(Area.ID),
nameof(Area.NameArea)),
Careers = new SelectList(_context.Careers,
nameof(Career.ID),
nameof(Career.CareerName)),
WorkTypes = _context.WorkTypes.ToList(),
Experiences = _context.Experiences.ToList()
};
ViewBag.LeftSlider = leftSlider;
return View(companies);
}
}
return NotFound();
}

How do I parse this type of JSON for Flutter?

I am fairly new to Flutter and have been running against a roadblock with this task. I am trying to get the following JSON into my Flutter app. I tried using QuickType.io but it gives me a class with AAPL in it and I don't want to have to make a class for every single stock on the market. What is they best approach, maybe still with using Quicktype, for parsing this JSON?
{"AAPL":{"assetType":"EQUITY","assetMainType":"EQUITY","cusip":"037833100","symbol":"AAPL","description":"Apple Inc. - Common Stock","bidPrice":126.82,"bidSize":800,"bidId":"K","askPrice":126.9,"askSize":1000,"askId":"P","lastPrice":126.82,"lastSize":100,"lastId":"K","openPrice":128.78,"highPrice":130.2242,"lowPrice":127.0,"bidTick":" ","closePrice":128.91,"netChange":-2.09,"totalVolume":111598531,"quoteTimeInLong":1610758795615,"tradeTimeInLong":1610758795615,"mark":127.14,"exchange":"q","exchangeName":"NASD","marginable":true,"shortable":true,"volatility":0.0083,"digits":4,"52WkHigh":138.789,"52WkLow":53.1525,"nAV":0.0,"peRatio":40.0668,"divAmount":0.82,"divYield":0.64,"divDate":"2020-11-06 00:00:00.000","securityStatus":"Normal","regularMarketLastPrice":127.14,"regularMarketLastSize":90964,"regularMarketNetChange":-1.77,"regularMarketTradeTimeInLong":1610744400773,"netPercentChangeInDouble":-1.6213,"markChangeInDouble":-1.77,"markPercentChangeInDouble":-1.3731,"regularMarketPercentChangeInDouble":-1.3731,"delayed":true}}
Please have a look at this video link which explain the easiest way to parse any json https://www.youtube.com/watch?v=FH4ckL37LHw
Parse Json:
class ClassName {
AAPL aAPL;
ClassName({this.aAPL});
ClassName.fromJson(Map<String, dynamic> json) {
aAPL = json['AAPL'] != null ? new AAPL.fromJson(json['AAPL']) : null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.aAPL != null) {
data['AAPL'] = this.aAPL.toJson();
}
return data;
}
}
class AAPL {
String assetType;
String assetMainType;
String cusip;
String symbol;
String description;
double bidPrice;
int bidSize;
String bidId;
double askPrice;
int askSize;
String askId;
double lastPrice;
int lastSize;
String lastId;
double openPrice;
double highPrice;
int lowPrice;
String bidTick;
double closePrice;
double netChange;
int totalVolume;
int quoteTimeInLong;
int tradeTimeInLong;
double mark;
String exchange;
String exchangeName;
bool marginable;
bool shortable;
double volatility;
int digits;
double d52WkHigh;
double d52WkLow;
int nAV;
double peRatio;
double divAmount;
double divYield;
String divDate;
String securityStatus;
double regularMarketLastPrice;
int regularMarketLastSize;
double regularMarketNetChange;
int regularMarketTradeTimeInLong;
double netPercentChangeInDouble;
double markChangeInDouble;
double markPercentChangeInDouble;
double regularMarketPercentChangeInDouble;
bool delayed;
AAPL(
{this.assetType,
this.assetMainType,
this.cusip,
this.symbol,
this.description,
this.bidPrice,
this.bidSize,
this.bidId,
this.askPrice,
this.askSize,
this.askId,
this.lastPrice,
this.lastSize,
this.lastId,
this.openPrice,
this.highPrice,
this.lowPrice,
this.bidTick,
this.closePrice,
this.netChange,
this.totalVolume,
this.quoteTimeInLong,
this.tradeTimeInLong,
this.mark,
this.exchange,
this.exchangeName,
this.marginable,
this.shortable,
this.volatility,
this.digits,
this.d52WkHigh,
this.d52WkLow,
this.nAV,
this.peRatio,
this.divAmount,
this.divYield,
this.divDate,
this.securityStatus,
this.regularMarketLastPrice,
this.regularMarketLastSize,
this.regularMarketNetChange,
this.regularMarketTradeTimeInLong,
this.netPercentChangeInDouble,
this.markChangeInDouble,
this.markPercentChangeInDouble,
this.regularMarketPercentChangeInDouble,
this.delayed});
AAPL.fromJson(Map<String, dynamic> json) {
assetType = json['assetType'];
assetMainType = json['assetMainType'];
cusip = json['cusip'];
symbol = json['symbol'];
description = json['description'];
bidPrice = json['bidPrice'];
bidSize = json['bidSize'];
bidId = json['bidId'];
askPrice = json['askPrice'];
askSize = json['askSize'];
askId = json['askId'];
lastPrice = json['lastPrice'];
lastSize = json['lastSize'];
lastId = json['lastId'];
openPrice = json['openPrice'];
highPrice = json['highPrice'];
lowPrice = json['lowPrice'];
bidTick = json['bidTick'];
closePrice = json['closePrice'];
netChange = json['netChange'];
totalVolume = json['totalVolume'];
quoteTimeInLong = json['quoteTimeInLong'];
tradeTimeInLong = json['tradeTimeInLong'];
mark = json['mark'];
exchange = json['exchange'];
exchangeName = json['exchangeName'];
marginable = json['marginable'];
shortable = json['shortable'];
volatility = json['volatility'];
digits = json['digits'];
d52WkHigh = json['52WkHigh'];
d52WkLow = json['52WkLow'];
nAV = json['nAV'];
peRatio = json['peRatio'];
divAmount = json['divAmount'];
divYield = json['divYield'];
divDate = json['divDate'];
securityStatus = json['securityStatus'];
regularMarketLastPrice = json['regularMarketLastPrice'];
regularMarketLastSize = json['regularMarketLastSize'];
regularMarketNetChange = json['regularMarketNetChange'];
regularMarketTradeTimeInLong = json['regularMarketTradeTimeInLong'];
netPercentChangeInDouble = json['netPercentChangeInDouble'];
markChangeInDouble = json['markChangeInDouble'];
markPercentChangeInDouble = json['markPercentChangeInDouble'];
regularMarketPercentChangeInDouble =
json['regularMarketPercentChangeInDouble'];
delayed = json['delayed'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['assetType'] = this.assetType;
data['assetMainType'] = this.assetMainType;
data['cusip'] = this.cusip;
data['symbol'] = this.symbol;
data['description'] = this.description;
data['bidPrice'] = this.bidPrice;
data['bidSize'] = this.bidSize;
data['bidId'] = this.bidId;
data['askPrice'] = this.askPrice;
data['askSize'] = this.askSize;
data['askId'] = this.askId;
data['lastPrice'] = this.lastPrice;
data['lastSize'] = this.lastSize;
data['lastId'] = this.lastId;
data['openPrice'] = this.openPrice;
data['highPrice'] = this.highPrice;
data['lowPrice'] = this.lowPrice;
data['bidTick'] = this.bidTick;
data['closePrice'] = this.closePrice;
data['netChange'] = this.netChange;
data['totalVolume'] = this.totalVolume;
data['quoteTimeInLong'] = this.quoteTimeInLong;
data['tradeTimeInLong'] = this.tradeTimeInLong;
data['mark'] = this.mark;
data['exchange'] = this.exchange;
data['exchangeName'] = this.exchangeName;
data['marginable'] = this.marginable;
data['shortable'] = this.shortable;
data['volatility'] = this.volatility;
data['digits'] = this.digits;
data['52WkHigh'] = this.d52WkHigh;
data['52WkLow'] = this.d52WkLow;
data['nAV'] = this.nAV;
data['peRatio'] = this.peRatio;
data['divAmount'] = this.divAmount;
data['divYield'] = this.divYield;
data['divDate'] = this.divDate;
data['securityStatus'] = this.securityStatus;
data['regularMarketLastPrice'] = this.regularMarketLastPrice;
data['regularMarketLastSize'] = this.regularMarketLastSize;
data['regularMarketNetChange'] = this.regularMarketNetChange;
data['regularMarketTradeTimeInLong'] = this.regularMarketTradeTimeInLong;
data['netPercentChangeInDouble'] = this.netPercentChangeInDouble;
data['markChangeInDouble'] = this.markChangeInDouble;
data['markPercentChangeInDouble'] = this.markPercentChangeInDouble;
data['regularMarketPercentChangeInDouble'] =
this.regularMarketPercentChangeInDouble;
data['delayed'] = this.delayed;
return data;
}
}
Use Provider https://pub.dev/packages/provider , this will automatically update UI class everytime data changes

Hamcrest - Matchers.hasProperty: how to check if a List of objects contains an object with a concrete value

I have the following problem with Hamcrest:
I have a List of Employee
List<Employee> employees = hamcrest.getEmployees();
where:
public class Employee {
private String name;
private int age;
private double salary;
public Employee(String name, int age, double salary) {
super();
this.name = name;
this.age = age;
this.salary = salary;
}
and:
public List<Employee> getEmployees() {
Employee e1 = new Employee("Adam", 39, 18000);
Employee e2 = new Employee("Jola", 26, 8000);
Employee e3 = new Employee("Kamil", 64, 7700);
Employee e4 = new Employee("Mateusz", 27, 37000);
Employee e5 = new Employee("Joanna", 31, 12700);
Employee e6 = null;
return Arrays.asList(e1, e2, e3, e4, e5, e6);
}
I'd like to check if there is an object with name = Mateusz in my list.
I've tried in such a way, but something get wrong:
#Test
public void testListOfObjectsContains() {
List<Employee> employees = hamcrest.getEmployees();
assertThat(employees, Matchers.anyOf(Matchers.containsInAnyOrder(Matchers.hasProperty("name", is("Mateusz")), Matchers.hasProperty("age", is(27)))));
}
How can I check this using Hamcrest?
I've spent over 2 hours to find the solution in Internet but unfortunately without success.
Thank you very much in advance!
You need the matcher hasItem
assertThat(
x,
hasItem(allOf(
Matchers.<Employee>hasProperty("name", is("Mateusz")),
Matchers.<Employee>hasProperty("age", is(27))
))
);
You can also use hasItems, contains or containsInAnyOrder :
assertThat(
x,
hasItems( // or contains or containsInAnyOrder
Matchers.<Employee>hasProperty("name", is("Mateusz")),
Matchers.<Employee>hasProperty("age", is(27))
)
);

Linq + nested GroupBy

We are using mySQL with WCF Restful service, we want to fetch our database content PACKAGEID wise...as mentioned below:
PackageId=2
{
StartRange = 1;
EndRange = 100;
IsDiscountAndChargeInPer = 1;
Discount =10;
ServiceCharge = 20;![enter image description here][1]
},
{
StartRange =101;
EndRange = 500;
IsDiscountAndChargeInPer = 1;
Discount =10;
ServiceCharge = 20;
}
PackageId=3
{
StartRange = 1;
EndRange = 100;
IsDiscountAndChargeInPer = 1;
Discount =10;
ServiceCharge = 20;
}
We have created a Result class to return result from out wcf service...for above service we have result class defined as below
[DataContract]
public class PackagePointRangeConfigurationResult : ResultBase
{
[DataMember]
public List<PackagePointRangeResult> Result;
}
public class PackagePointRangeResult
{
public int PackageId { get; set; }
public List<PointPlanInfo> Result { get; set; }
}
For fetching record we use following linq query:
var result = (from planinfo in db.mst_pointplan_info
join entityType in db.mst_entity_type
on planinfo.entityId equals entityType.id
where planinfo.entityId == entityId
&& planinfo.is_deleted != true
&& planinfo.system_id == systemId
&& entityType.enity_enum_id == entityId
group planinfo by planinfo.package_id into gplan
select new PackagePointRangeConfigurationResult
{
Result = (from planinfo in gplan
select new PackagePointRangeResult
{
PackageId = planinfo.package_id,
PointPlanInfo = (from pointPlanInfo in gplan
select new PointPlanInfo
{
StartRange = planinfo.start_range,
EndRange = planinfo.end_range,
IsDiscountAndChargeInPer = planinfo.is_discount_and_charge_in_per,
Discount = planinfo.discount,
ServiceCharge = planinfo.servicecharge,
AtonMerchantShare =planinfo.aton_merchant_share,
CommunityShare = planinfo.community_share
}).ToList()
}).ToList()
}).FirstOrDefault();
But it gives me below error:
LINQ to Entities does not recognize the method 'System.Collections.Generic.List1[PointPlanInfo] ToList[PointPlanInfo](System.Collections.Generic.IEnumerable1[PointPlanInfo])' method, and this method cannot be translated into a store expression.

Unsupported overload used for query operator 'Intersect'

I am able to do this query just fine with the test repository which is In Memory
when I move to the sqlRepository I get this error
Unsupported overload used for query operator 'Intersect'.
I assume it is because sending the query to sql is too complicated for Linq to Sql to do when it is not dealing with the Model.Model.Talent Type. Is there some way around doing a search like this with Intersect?
thanks
public class TalentService : ITalentService
{
ITalentRepository _repository = null;
private IQueryable<Talent> BasicSearch(string searchExpression)
{
IQueryable<Talent> t;
string[] sa = searchExpression.Trim().ToLower().Replace(" ", " ").Split(' ');
t = _repository.GetTalents();
foreach (string s in sa)
{
t = t.Intersect(AddBasicSearch(s), new TalentComparer());
}
return t;
}
private IQueryable<Talent> AddBasicSearch(string s)
{
IQueryable<Talent> t2 = _repository.GetTalents()
.Where(tal => tal.EyeColor.ToString().ToLower().Contains(s)
|| tal.FirstName.ToLower().Contains(s)
|| tal.LastName.ToLower().Contains(s)
|| tal.LanguagesString.ToLower().Contains(s)
);
return t2;
}
}
public class SqlTalentRepository:ITalentRepository
{
public IQueryable<Model.Model.Talent> GetTalents()
{
var tal = from t in _db.Talents
let tLanguage = GetTalentLanguages(t.TalentID)
where t.Active == true
select new Model.Model.Talent
{
Id = t.TalentID,
FirstName = t.FirstName,
LastName = t.LastName,
TalentLanguages = new LazyList<Model.Model.TalentLanguage>(tLanguage),
LanguagesString = t.TalentLanguages.ToLanguageNameString(_LanguageRepository.GetLanguages())
};
return tal ;
}
public IQueryable<Model.Model.TalentLanguage> GetTalentLanguages(int iTalentId)
{
var q = from y in this.talentLanguageList
let Languages = _LanguageRepository.GetLanguages()
where y.TalentId == iTalentId
select new Model.Model.TalentLanguage
{
TalentLanguageId = y.TalentLanguageId,
TalentId = y.TalentId,
LanguageId = y.LanguageId,
Language = Languages.Where(x => x.LanguageId == y.LanguageId).SingleOrDefault()
};
return q.AsQueryable<Model.Model.TalentLanguage>();
}
}
public static class TalentExtensions
{
public static string ToLanguageNameString(this IEnumerable<TalentLanguage> source
, IEnumerable<Model.Model.Language> allLanguages)
{
StringBuilder sb = new StringBuilder();
const string del = ", ";
foreach (TalentLanguage te in source)
{
sb.AppendFormat("{0}{1}", allLanguages
.Where(x => x.LanguageId == te.LanguageID).SingleOrDefault().LanguageName, del);
}
string sReturn = sb.ToString();
if (sReturn.EndsWith(del))
sReturn = sReturn.Substring(0, sReturn.Length - del.Length);
return sReturn;
}
}
public class TestTalentRepository : ITalentRepository
{
IList<Talent> talentList;
public TestTalentRepository(ILanguageRepository _LanguageRepo )
{
this._LanguageRepository = _LanguageRepo;
talentList = new List<Talent>();
talentLanguageList = new List<TalentLanguage>();
for (int i = 0; i < 55; i++)
{
var t = new Talent();
t.Id = i;
t.FirstName = (i % 3 == 0) ? "Ryan" : "Joe";
t.LastName = (i % 2 == 0) ? "Simpson" : "Zimmerman";
AddLanguagesToTestTalent(i, t);
talentList.Add(t);
}
}
private void AddLanguagesToTestTalent(int i, Talent t)
{
IList<Language> Languages = _LanguageRepository.GetLanguages().ToList<Language>();
Random rLanguages = new Random();
int numLanguages = rLanguages.Next(Languages.Count - 1) + 1;
t.TalentLanguages = new LazyList<TalentLanguage>();
for (int j = 0; j < numLanguages; j++)
{
var x = new TalentLanguage();
x.TalentLanguageId = j;
x.TalentId = i;
Random random2 = new Random();
int rand = random2.Next(Languages.Count);
var y = Languages.ElementAtOrDefault(rand);
Languages.RemoveAt(rand);
x.Language = y;
x.LanguageId = y.LanguageId;
t.TalentLanguages.Add(x);
}
}
public IQueryable<Talent> GetTalents()
{
var ts = from t in this.talentList
let tLanguage = GetTalentLanguages(t.Id)
where t.Active == true
select new Model.Model.Talent
{
Id = t.Id,
FirstName = t.FirstName,
LastName = t.LastName,
TalentLanguages = new LazyList<Model.Model.TalentLanguage>(tLanguage),
LanguagesString = t.TalentLanguages.ToLanguageNameString(_LanguageRepository.GetLanguages()),
City = t.City,
};
return ts.AsQueryable<Model.Model.Talent>();
}
public IQueryable<Model.Model.TalentLanguage> GetTalentLanguages(int iTalentId)
{
var q = from y in this.talentLanguageList
let Languages = _LanguageRepository.GetLanguages()
where y.TalentId == iTalentId
select new Model.Model.TalentLanguage
{
TalentLanguageId = y.TalentLanguageId,
TalentId = y.TalentId,
LanguageId = y.LanguageId,
Language = Languages.Where(x => x.LanguageId == y.LanguageId).SingleOrDefault()
};
return q.AsQueryable<Model.Model.TalentLanguage>();
}
}
If you're trying to find entries which match all of those criteria, you just need multiple where clauses:
private static readonly char[] SplitDelimiters = " ".ToCharArray();
private IQueryable<Talent> BasicSearch(string search)
{
// Just replacing " " with " " wouldn't help with "a b"
string[] terms = search.Trim()
.ToLower()
.Split(SplitDelimiters,
StringSplitOptions.RemoveEmptyEntries);
IQueryable<Talent> query = _repository.GetTalents();
foreach (string searchTerm in terms)
{
query = AddBasicSearch(query, searchTerm);
}
return query;
}
private IQueryable<Talent> AddBasicSearch(IQueryable<Talent> query, string s)
{
return query.Where(tal =>
tal.EyeColor.ToString().ToLower().Contains(s)
|| tal.FirstName.ToLower().Contains(s)
|| tal.LastName.ToLower().Contains(s)
|| tal.LanguagesString.ToLower().Contains(s)
);
}