how to convert list object to list string( getting error Unable to cast object of type) - c#

Hi Friends i have a list of objects private static List<Transaction> transactions;
i am querying through the list to filter the data with some criteria. but i am not able to return the list string. i am getting the error
Unable to cast object of type
<>f__AnonymousType1`6[System.Int32,System.String,System.String,System.String,System.String,System.String]
to type 'System.String'.
my plan is to make the datagridview source this list like dataGridView2.DataSource = BasicClass.banksearch("ABC");
public static List<string> banksearch(string bankname, string sdate = null, string edate = null, string condition = null)
{
List<string> returnstr = new List<string>();
if (sdate == null && edate == null)//only bank
{
returnstr = transactions
.Where(t => t.BankName == bankname)
.Select(t => new
{
TransactionID = t.TransactionID,
BankName = t.BankName,
TemplateModel = t.TemplateModel,
Date = t.Date.ToString(),
PayeeName = t.PayeeName,
Amount = t.Amount.ToString()
}).Cast<String>().ToList();
}
return returnstr;
}
my class file is
class Transaction
{
public int TransactionID { get; set; }
public string BankName { get; set; }
public string TemplateModel { get; set; }
public DateTime Date { get; set; }
public string PayeeName { get; set; }
public decimal Amount { get; set; }
}
Please give me idea to get the result

There is no need to project the entire collection onto an Anonymous Object.
All you're actually doing is filtering by bankname:
public static List<Transaction> BankSearch(string bankname, string sdate = null, string edate = null, string condition = null)
{
List<Transaction> filteredTransactions = new List<Transaction>();
if (sdate == null && edate == null)
{
filteredTransactions = transactions.Where(t => t.BankName == bankname).ToList();
}
return filteredTransactions;
}

You don't need to convert to a string in order to use this result as a datasource (although if you actually need a string I can show you how to create a formatted string instead of an anonymous class object). You likely need something like this:
public static List<Transaction> banksearch(string bankname, string sdate = null, string edate = null, string condition = null)
{
if (sdate == null && edate == null)//only bank
{
return transactions // type: List<Transaction>
.Where(t => t.BankName == bankname)
.ToList();
} else {
return new List<Transaction>();
}
}

Related

Compare 2 Columns in DataTable to 2 Columns in List and build a new List with certain criteria

I have DataTable
public static DataTable SubProjects = new DataTable();
public static DataTable GetSubProjects
{
get { return SubProjects; }
}
it comes from database so columns are as follows
select ProjectN,ProjectSubN,ProjectM
and list:
public class SubProjectsList
{
public string ProjectNumber { get; set; }
public string SubProjectNumber { get; set; }
public string SubProjectName { get; set; }
public string ProjectManager { get; set; }
public int ObjectID { get; set; }
public SubProjectsList(string ProjectNumber, string SubProjectNumber, string SubProjectName, string ProjectManager, int ObjectID)
{
this.ProjectNumber = ProjectNumber;
this.SubProjectNumber = SubProjectNumber;
this.SubProjectName = SubProjectName;
this.ProjectManager = ProjectManager;
this.SubProjectNumber = SubProjectNumber;
this.ObjectID = ObjectID;
}
}
public static List<SubProjectsList> DeliverySubProjectList = new List<SubProjectsList>();
Ultimately I would like to get all results to new List where
ProjectN + ProjectSubN (DataTable) = ProjectNumber + SubProjectNumber (List) &&
ProjectM (DataTable) != ProjectManager (List)
As an output I need to get ProjectNumber, SubProjectNumber, ProjectM, ProjectManager. Basically I need to catch ProjectM and ProjectManager that does not match for one sub-project. I could have done it this way
var SubProjectResult = SubProjects.AsEnumerable()
.Where(x => DeliverySubProjectList.Any(y =>
y.ProjectNumber.Trim() + y.SubProjectNumber == x.Field<string>("ProjectN").Trim() + x.Field<string>("ProjectSubN").Trim() &&
!string.Equals(y.ProjectManager.Trim(), x.Field<string>("ProjectM").Trim(), StringComparison.CurrentCultureIgnoreCase)))
.Select(x => new
{
ProjectN = x.Field<string>("ProjectN"),
ProjectN = x.Field<string>("ProjectSubN"),
ProjectM = x.Field<string>("ProjectM"),
ProjectM = x.ProjectManager // This is not possible
})
.OrderBy(o => o.ProjectN).ToList();
but
ProjectM = x.ProjectManager // This is not possible
is wrong and does not compile. So I can't get ProjectManager from List where ProjectN + ProjectSubN (DataTable) = ProjectNumber + SubProjectNumber (List) match but ProjectManager does not match. Do I need to Concat DataTable and List together first? I have tried this
var myList1 = SubProjects.AsEnumerable().Concat(DeliverySubProjectList).ToList();
but getting an error
Severity Code Description Project File Line Suppression State
Error CS1929 'EnumerableRowCollection' does not contain a
definition for 'Concat' and the best extension method overload
'Queryable.Concat(IQueryable,
IEnumerable)' requires a receiver of type
'IQueryable'
I think this should give you what you are looking for. You might need to add extra null checks and I am also not very sure about that's how you want to add string values from the list and the data table:
public class ResultModel
{
public string ProjectNumber { get; set; }
public string SubProjectNumber { get; set; }
public string ProjectM { get; set; }
public string ProjectManager { get; set; }
}
...
...
static void Main(string[] args)
{
List<SubProjectsList> DeliverySubProjectList = // populate list
DataTable SubProjects = // populate datatable
List<ResultModel> results = GetResults(DeliverySubProjectList, SubProjects).ToList();
}
private static IEnumerable<ResultModel> GetResults(List<SubProjectsList> DeliverySubProjectList, DataTable SubProjects)
{
return SubProjects.AsEnumerable().Select(row =>
{
var listItem = DeliverySubProjectList.FirstOrDefault(item =>
{
return item.ProjectNumber + item.SubProjectNumber == row["ProjectN"].ToString() + row["ProjectSubN "].ToString()
&& !item.ProjectManager.Equals(row["ProjectM"].ToString());
});
if (listItem != null)
{
return new ResultModel
{
ProjectNumber = row["ProjectN"].ToString(),
SubProjectNumber = listItem.SubProjectNumber,
ProjectM = row["ProjectM"].ToString(),
ProjectManager = listItem.ProjectManager
};
}
else
{
return null;
}
})
.Where(res => res != null);
}

Compare two Complex Objects in c#

I am trying to compare two objects and want to identify the difference in objects.
It works fine if I don't use List. But when I use List, Although the List in both objects are equal, it says it's not equal and go to check for List difference. Since, for now, I don't have the condition for list comparison it crashes and gives me this exception System.Reflection.TargetParameterCountException: 'Parameter count mismatch.'
I have taken help from one of the stackoverflow post from here. Here is my code which I have written so far.
public class Program
{
public static void Main()
{
Employee emp1 = OldEmployee();
Employee emp2 = NewEmployee();
var list = GetDifferingProperties(emp1, emp2);
foreach (var s in list)
Console.WriteLine(s);
}
public static IList<string> GetDifferingProperties(object source, object target)
{
var sourceType = source.GetType();
var sourceProperties = sourceType.GetProperties();
var targetType = target.GetType();
var targetProperties = targetType.GetProperties();
var result = new List<string>();
foreach (var property in
(from s in sourceProperties
from t in targetProperties
where s.Name == t.Name &&
s.PropertyType == t.PropertyType &&
!Equals(s.GetValue(source, null), t.GetValue(target, null))
select new { Source = s, Target = t }))
{
// it's up to you to decide how primitive is primitive enough
if (IsPrimitive(property.Source.PropertyType))
{
result.Add(property.Source.Name);
}
else
{
foreach (var subProperty in GetDifferingProperties(
property.Source.GetValue(source, null),
property.Target.GetValue(target, null)))
{
result.Add(property.Source.Name);
}
}
}
return result;
}
private static bool IsPrimitive(Type type)
{
return type == typeof(string)
|| type == typeof(int) || type == typeof(int?)
|| type == typeof(double) || type == typeof(double?)
|| type == typeof(bool) || type == typeof(bool?)
|| type == typeof(Guid) || type == typeof(Guid?)
|| type == typeof(DateTime) || type == typeof(DateTime?);
}
public static string GetPropertyDisplayName(PropertyInfo pi)
{
var dp = pi.GetCustomAttributes(typeof(DisplayNameAttribute), true).Cast<DisplayNameAttribute>().SingleOrDefault();
return dp != null ? dp.DisplayName : pi.Name;
}
private static Employee NewEmployee()
{
var contactDetail = new ContactDetails();
contactDetail.ContactNumber = "123456789";
var employeeAddress = new Address();
employeeAddress.AddressLine1 = "Microsoft Corporation";
employeeAddress.AddressLine2 = "One Microsoft Way";
employeeAddress.City = "Redmond";
employeeAddress.State = "WA";
employeeAddress.Zip = "98052-6399";
employeeAddress.ContactDetails = new List<ContactDetails>() { contactDetail };
var employee = new Employee();
employee.FirstName = "Bill";
employee.LastName = "Gates";
employee.MiddleName = "Middle Name";
employee.IsActive = true;
employee.JoinDate = new DateTime(2015, 10, 15);
employee.ReleaseDate = new DateTime(2015, 10, 15);
employee.EmployeeAddress = employeeAddress;
return employee;
}
private static Employee OldEmployee()
{
var contactDetail = new ContactDetails();
contactDetail.ContactNumber = "123456789";
var employeeAddress = new Address();
employeeAddress.AddressLine1 = "Microsoft Corporation";
employeeAddress.AddressLine2 = "One Microsoft Way";
employeeAddress.City = "Redmond";
employeeAddress.State = "WA";
employeeAddress.Zip = "98052-6399";
employeeAddress.ContactDetails = new List<ContactDetails>() { contactDetail };
var employee = new Employee();
employee.FirstName = "Bill";
employee.LastName = "Gates";
employee.MiddleName = "Middle Name";
employee.IsActive = true;
employee.JoinDate = new DateTime(2015, 10, 15);
employee.ReleaseDate = new DateTime(2015, 10, 15);
employee.EmployeeAddress = employeeAddress;
return employee;
}
}
public class ContactDetails
{
public string ContactNumber { get; set; }
}
public class Address
{
public string AddressLine1 { get; set; }
public string AddressLine2 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zip { get; set; }
public bool IsActive { get; set; }
public List<ContactDetails> ContactDetails { get; set; }
}
public class Employee
{
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
public bool IsActive { get; set; }
public DateTime JoinDate { get; set; }
public DateTime? ReleaseDate { get; set; }
public Address EmployeeAddress { get; set; }
}
If I comment out the line employeeAddress.ContactDetails = new List<ContactDetails>() { contactDetail }; from oldEmployee and newEmployee, it works fine, and if there is any difference in EmployeeAddress it identifies it, and if there isn't any difference it doesn't. But if I uncomment this line employeeAddress.ContactDetails = new List<ContactDetails>() { contactDetail }; it takes out EmployeeAddress as it has difference, although it doesn't. Can some one please suggest what I am missing, I have spent a lot of time to identify the issue.
My Target to Achieve is, to make a list of properties that has a difference in Employee Object, for Example,
If FirstName in Employee has difference result list should
contain only FirstName
If FirstName in Employee and AddressLine1 in EmployeeAddress has difference result list should contain (FirstName, EmployeeAddress)
Similarly, If FirstName in Employee and ContactNumber in ContactDetails which is a List in Address has difference result list should contain (FirstName, EmployeeAddress), In this case result list still contains EmployeeAddress because ContactNumber is in EmployeeAddress which is in Employee, So our main focus is to get parent Properties that has difference is source and target object.
Point 1 and Point 2 are working as Expected. Iff I comment out employeeAddress.ContactDetails = new List<ContactDetails>() { contactDetail }; because it causing exception and also it coming with change although it doesn't have any change in source and target.
Any help would be highly appreciated, or you can suggest me some other way of implementation too.

Orderby on left join null value

Following situation:
Table of users
Table of addresses
The user has a single optional reference to the address table (=left join)
The query to fetch the data is:
IQueryable<User> query =
from u in _dbContext.Users
join a in _dbContext.Address on u.AddressId equals a.Id into address
from addresses in address.DefaultIfEmpty()
select new User(u, a);
Now I want to do a sorting on the query based on the municipality of the address
query = query.OrderBy(u => u.Address.Municipality);
The problem is that the Address can be a null value (as the address is optional) and for that reason it is throwing following exception.
NullReferenceException: Object reference not set to an instance of an object.
Is there a way to order on the municipality knowing that it can be null?
Already tried following things with same outcome:
query = query.OrderBy(u => u.Address.Municipality ?? "");
query = query.OrderBy(u => u.Address == null).ThenBy(u => u.Address.Municipality);
You can use
query = query.OrderBy(u => u.Address.Municipality.HasValue);
You can write your comparer like this:
public class One
{
public int A { get; set; }
}
public class Two
{
public string S { get; set; }
}
public class T
{
public One One { get; set; }
public Two Two { get; set; }
}
public class OrderComparer : IComparer<Two>
{
public int Compare(Two x, Two y)
{
if (((x == null) || (x.S == null)) && ((y == null) || (y.S == null)))
return 0;
if ((x == null) || (x.S == null))
return -1;
if ((y == null) || (y.S == null))
return 1;
return x.S.CompareTo(y.S);
}
}
static void Main(string[] args)
{
var collection = new List<T> {
new T{ One = new One{A=1}, Two = new Two{ S="dd" } },
new T{ One = new One{A=5}, Two = null },
new T{ One = new One{A=0}, Two = new Two{ S=null } },
new T{ One = new One{A=6}, Two = new Two{ S="aa" } },
};
var comparer = new OrderComparer();
collection = collection.OrderBy(e => e.Two, comparer).ToList();
}
But in your case you have to write var collection = query.AsEnumerable().OrderBy(x=>x.Address).
Also there is other method:
var result = query.Where(x=>x.Address==null || x.Address.Municipality==null)
.Union(query.Where(x.Address!=null && x.Address.Municipality!=null).OrderBy(x=>x.Address.Municipality));
I create a simple demo and it works well when I add nullable foreign key to the two tables.
Besides, I do not understabd what is select new User(u, a); in your code.
Below is my sample code:
Models:
public class User
{
public int Id { get; set; }
public string Name { get; set; }
[ForeignKey("Address")]
public int? AddressId { get; set; }
public Address Address { get; set; }
}
public class Address
{
public int Id { get; set; }
public string AddressName { get; set; }
public string Municipality { get; set; }
}
Action:
IQueryable<User> query =
from u in _context.Users
join a in _context.Address on u.AddressId equals a.Id into address
from addresses in address.DefaultIfEmpty()
select new User
{
Id = u.Id,
Name = u.Name,
AddressId = u.AddressId,
Address = addresses
};
query = query.OrderBy(u => u.Address.Municipality);

Nested IEnumerable collections within Class filtering on multiple conditions

I may not being using the correct term "nested", but you can see the 2 classes I have below. IEnumerable<OperationTask> is in the IEnumerable<AxApp>.
I hope I can explain this correctly:
I have a method that is reading values from a txt file into a string[]
string[] appNames = _appNamesRepository.GetAppNameListFromInputFile(fileName);
Then I create an IEnumerable<AxApp> collection with a method that reads a SQL table and returns the AxApp properties for each app value in the txt file.
IEnumerable<AxApp> allAxApps = _axAppRepository.GetAllAxAppsInList(appNames);
I need to filter the IEnumerable<AxApp> collection based on specific criteria from values in the IEnumerable<OperationTask>. I can get a basic lambda search to work, but I can't return the correct result if I have more than a couple values I'm basing this on.
For example the below will only return an IEnumerable<AxApp> if the appid, operationType, and operationStatus.Incomplete are NOT in IEnumerable<OperationTasks>.
var test = allAxApps.Where(app =>
!app.operationTasks
.Any(task => task.appId == app.appid &&
task.operationType == operationType &&
task.operationStatus != Status.Incomplete));
HOWEVER, I need to go a step further, if the operationType == "Differential", I can only return the AxApp IF IN IEnmerable<OperationTask> there is a collection where type = "NewConversion", status = "Complete", but NO type = "Finish", but can include types = "Differential"
public class AxApp
{
public AxApp()
{
}
public AxApp(int id, string appname, string dlname)
{
this.appname = appname;
appid = id;
this.dlname = dlname;
}
public string appname { get; set; }
public int appid { get; set; }
public string dlname { get; set; }
public string dtname { get; set; }
public int flags { get; set; }
public IEnumerable<AxDlsd> dlsdRecords { get; set; }
public IEnumerable<AxDl> dlRecords { get; set; }
public IEnumerable<OperationTask> operationTasks { get; set; }
public DateTime startMerge { get; set; }
public DateTime endMerge { get; set; }
}
public class OperationTask
{
public int operationId { get; set; }
public int appId { get; set; }
public OperationType operationType { get; set; }
public Status operationStatus { get; set; }
public DateTime startTime { get; set; }
public DateTime endTime { get; set; }
}
Method that returns the AppData from any value in the string[]
public IEnumerable<AxApp> GetAllAxAppsInList(string[] appNamesInput)
{
string query = #"SELECT appid, appname, dlname, dtname, flags FROM dbo.ae_apps WHERE appname = #_appname";
string opQuery = #"SELECT operationId, appId, operationType, operationStatus, startTime, endTime FROM dbo.RDS_ConversionOperationsHistory WHERE appid = #_appId";
using (var connection = _dbConnectionFactory.GetAxDbConnection())
{
foreach (string appname in appNamesInput)
{
AxApp result = connection.QuerySingle<AxApp>(query, new { _appname = appname });
result.operationTasks = connection.Query<OperationTask>(opQuery, new { _appId = result.appid });
yield return result;
}
}
}
IEnumerable for AxApp/OperationTask
[0] = {RDS.Conversion.UtilityLibrary.Models.AxApp}
[0] {RDS.Conversion.UtilityLibrary.Models.AxApp} RDS.Conversion.UtilityLibrary.Models.AxApp
appid 1 int
appname "PLIC_CENT_1" string
dlRecords null System.Collections.Generic.IEnumerable<RDS.Conversion.UtilityLibrary.Models.AxDl
dlname "ae_dlsd1_SIM" string
dlsdRecords null System.Collections.Generic.IEnumerable<RDS.Conversion.UtilityLibrary.Models.AxDlsd>
dtname "ae_dt1" string
endMerge {1/1/0001 12:00:00 AM} System.DateTime
flags 16384 int
operationTasks Count = 3 System.Collections.Generic.IEnumerable<RDS.Conversion.UtilityLibrary.Models.OperationTask> {System.Collections.Generic.List<RDS.Conversion.UtilityLibrary.Models.OperationTask>}
startMerge {1/1/0001 12:00:00 AM} System.DateTime
operationTasks Count = 3 System.Collections.Generic.IEnumerable<RDS.Conversion.UtilityLibrary.Models.OperationTask> {System.Collections.Generic.List<RDS.Conversion.UtilityLibrary.Models.OperationTask>}
[0] {RDS.Conversion.UtilityLibrary.Models.OperationTask} RDS.Conversion.UtilityLibrary.Models.OperationTask
appId 1 int
endTime {1/1/0001 12:00:00 AM} System.DateTime
operationId 18 int
operationStatus Complete RDS.Conversion.UtilityLibrary.Models.Status
operationType NewConversion RDS.Conversion.UtilityLibrary.Models.OperationType
startTime {9/28/2018 12:53:51 PM} System.DateTime
I'm not sure if this is what you're looking for but, it may get you in the right direction.
test = allAxApps.Where(app =>
{
var tasks = app.operationTasks.ToList();
var differentialCondition = false;
if (operationType == OperationType.Differential)
{
var hasCompletedNewConversion = tasks.Any(task =>
task.operationType == OperationType.NewConversion &&
task.operationStatus == Status.Complete);
var hasFinish = tasks.Any(task => task.operationType == OperationType.Finish);
differentialCondition = hasCompletedNewConversion && !hasFinish;
}
var hasIncomplete = tasks.Any(task =>
task.appId == app.appid &&
task.operationType == operationType &&
task.operationStatus == Status.Incomplete);
return differentialCondition && !hasIncomplete;
});

Elastic search nest dynamic query with object initializer NEST 5.x

Hi I'm a new to elastic nest API and I'm using nest 5.x. I'm currently developing some kind of advanced search page so when user doesn't check a criteria i don't have to include that filter on my query. I'm trying to combine 2 queries under must operator with object initializer approach using nest. How to achieve it? I'm following the example on [https://www.elastic.co/guide/en/elasticsearch/client/net-api/current/bool-queries.html]
var secondSearchResponse = client.Search(new
SearchRequest {
Query = new TermQuery { Field = Field(p => p.Name), Value = "x" } &&
new TermQuery { Field = Field(p => p.Name), Value = "y" } });
But it doesnt work cause Field class doesnt accept type arguments.
I also tried to followed this approach from this topic
[Nest Elastic - Building Dynamic Nested Query
here is my code
public HttpResponseMessage GetSearchResult([FromUri] SearchModels queries)
{
try
{
///
string result = string.Empty;
result += "queryfields + " + queries.queryfields == null ? string.Empty : queries.queryfields;
result += "datefrom + " + queries.datefrom == null ? string.Empty : queries.datefrom;
result += "dateto + " + queries.dateto == null ? string.Empty : queries.dateto;
result += "emitentype + " + queries.emitentype == null ? string.Empty : queries.emitentype;
QueryContainer andQuery = null;
//List<QueryContainer> QueryContainers = new List<QueryContainer>();
IDXNetAnnouncement record = new IDXNetAnnouncement
{
kode_emiten = queries.kodeemiten
};
#region keyword
if (!string.IsNullOrEmpty(queries.queryfields))
{
var val = queries.queryfields;
TermQuery tq = new TermQuery
{
Field = queries.queryfields,
Value = val
};
if (andQuery == null)
andQuery = tq;
else
andQuery &= tq;
//QueryContainers.Add(tq);
}
#endregion keyword
#region kodeemiten
if (!string.IsNullOrEmpty(queries.kodeemiten))
{
var val = queries.kodeemiten;
TermQuery tq = new TermQuery
{
Name = "kode_emiten",
Field = record.kode_emiten,
Value = val
};
if (andQuery == null)
andQuery = tq;
else
andQuery &= tq;
//QueryContainers.Add(tq);
}
#endregion
#region date
if (!string.IsNullOrEmpty(queries.datefrom) && !string.IsNullOrEmpty(queries.dateto))
{
DateRangeQuery dq = new DateRangeQuery();
dq.Name = "tglpengumuman";
dq.LessThanOrEqualTo = DateMath.Anchored(queries.dateto);
dq.GreaterThanOrEqualTo = DateMath.Anchored(queries.datefrom);
dq.Format = "dd/mm/yyyy";
if (andQuery == null)
andQuery = dq;
else
andQuery &= dq;
//QueryContainers.Add(dq);
}
#endregion keyword
var reqs = (ISearchResponse<IDXNetAnnouncement>)null;
if (andQuery != null)
{
reqs = conn.client.Search<IDXNetAnnouncement>(s => s
.AllIndices()
.AllTypes()
.From(queries.indexfrom)
.Size(queries.pagesize)
.Query(q => q.Bool(qb => qb.Must(m => m.MatchAll() && andQuery))));
//var json = conn.client.Serializer.SerializeToString(reqs.ApiCall.ResponseBodyInBytes);
}
else
{
reqs = conn.client.Search<IDXNetAnnouncement>(s => s
.AllIndices()
.AllTypes()
.From(queries.indexfrom)
.Size(queries.pagesize)
.Query(m => m.MatchAll()));
}
//var reqstring = Encoding.UTF8.GetString(conn.client.);
var reslts = this.conn.client.Serializer.SerializeToString(reqs,SerializationFormatting.Indented);
var resp = new HttpResponseMessage()
{
Content = new StringContent(reslts)
};
resp.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
return resp;
}
catch (Exception e)
{
var resp = new HttpResponseMessage()
{
Content = new StringContent(e.ToString())
};
resp.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
return resp;
}
}
But that returns zero result. How to achieve this? Thx anyway.
EDIT :
This is the params variabel definition. Its apoco model of search keywords
public class SearchModels
{
public string queryfields { get; set; }
public string datefrom { get; set; }
public string dateto { get; set; }
public string emitentype { get; set; }
public string kodeemiten { get; set; }
public string issuercode { get; set; }
public int indexfrom { get; set; }
public int pagesize { get; set; }
}
IDXNetAnnouncement is a poco model of search result. Its actualy a document type which is stored on the elastic server
public class IDXNetAnnouncement
{
public string perihalpengumuman { get; set; }
public string attachments { get; set; }
public string createddate { get; set; }
public bool efekemiten_spei { get; set; }
public string jmsxgroupid { get; set; }
public string tglpengumuman { get; set; }
public object errordescription { get; set; }
public string ESversion { get; set; }
public int oldfinalid { get; set; }
public bool efekemiten_etf { get; set; }
public object errorcode { get; set; }
public string jenisemiten { get; set; }
public int pkid { get; set; }
public string judulpengumuman { get; set; }
public string form_id { get; set; }
public bool efekemiten_eba { get; set; }
public string jenispengumuman { get; set; }
public string nopengumuman { get; set; }
public string kode_emiten { get; set; }
public string divisi { get; set; }
public string EStimestamp { get; set; }
public bool efekemiten_obligasi { get; set; }
public long finalid { get; set; }
public bool efekemiten_saham { get; set; }
public string kodedivisi { get; set; }
public string SearchTerms
{
get
{
return string.Format("{0} {1} {2}", judulpengumuman, kode_emiten, nopengumuman);
}
}
}
But it doesnt work cause Field class doesnt accept type arguments.
You need to ensure that you include a using static directive for Nest.Infer i.e.
using static Nest.Infer;
with the rest of the using directives.
.Query(q => q.Bool(qb => qb.Must(m => m.MatchAll() && andQuery))));
No need to wrap in a Must(), just do
.Query(q => q.MatchAll() && andQuery)
which will wrap both queries in a bool query must clause. You also don't need to null check andQuery because NEST is smart enough to not combine the two queries if either or both are null.
if (!string.IsNullOrEmpty(queries.queryfields))
{
var val = queries.queryfields;
TermQuery tq = new TermQuery
{
Field = queries.queryfields,
Value = val
};
if (andQuery == null)
andQuery = tq;
else
andQuery &= tq;
//QueryContainers.Add(tq);
}
NEST has the concept of conditionless queries so you don't need to check it queries.queryfields is null or empty, simply build the query and add it to andQuery. So it would become
var val = queries.queryfields;
andQuery &= new TermQuery
{
Field = queries.queryfields,
Value = val
};
Aside
All of the NEST documentation is generated from source code; you can trace back to the original source file by clicking on any edit link within the documentation. This will take you to a github page, such as this one for bool queries. From here, the document contains an important note that links back to the original source.

Categories