I have written this program in C# for an assignment I have due tonight. What I have to do is create a class named "Employee" have have the information display on a List Box. I believe that I have everything together, and I am not showing any syntax errors, but when I attempt to run the program, nothing happens. Do you think you can help me find out why its not working? All that appears is a blank list box. Here is my code on my Form1.cs:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Adam_Zeidan___IS_204___HW10CH9_4
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
listBox1.Items.Add("Name\t\tID Number\tDepartment\tPosition");
Employee emp1 = emp1 = new Employee();
emp1.Name = "Susan Meyers";
emp1.IdNumber = 47899;
emp1.Department = "Accounting";
emp1.Position = "Vice President";
listBox1.Items.Add(emp1.Name + "\t" + emp1.IdNumber + "\t\t" + emp1.Department + "\t" + emp1.Position);
Employee emp2 = emp2 = new Employee();
emp2.Name = "Mark Jones";
emp2.IdNumber = 39119;
emp2.Department = "IT";
emp2.Position = "Programmer";
listBox1.Items.Add(emp2.Name + "\t" + emp2.IdNumber + "\t\t" + emp2.Department + "\t" + emp2.Position);
Employee emp3 = emp3 = new Employee();
emp3.Name = "Joy Rogers";
emp3.IdNumber = 81774;
emp3.Department = "Manufacturing";
emp3.Position = "Engineer";
listBox1.Items.Add(emp3.Name + "\t" + emp3.IdNumber + "\t\t" + emp3.Department + "\t" + emp3.Position);
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}
Now this is the Employee.cs code that I used to create the class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Adam_Zeidan___IS_204___HW10CH9_4
{
class Employee
{
private string _name;
private int _idNumber;
private string _department;
private string _position;
public Employee()
{
_name = "";
_idNumber = 0;
_department = "";
_position = "";
}
public Employee(string name, int idNumber)
{
_name = name;
_idNumber = idNumber;
_department = "";
_position = "";
}
public Employee(string name, int idNumber, string department, string position)
{
_name = name;
_idNumber = idNumber;
_department = department;
_position = position;
}
public string Name
{
get
{
return _name;
}
set
{
_name = value;
}
}
public int IdNumber
{
get
{
return _idNumber;
}
set
{
_idNumber = value;
}
}
public string Department
{
get
{
return _department;
}
set
{
_department = value;
}
}
public string Position
{
get
{
return _position;
}
set
{
_position = value;
}
}
}
Do you think you can help me find out why its not working?
Change the following lines
Employee emp1 = emp1 = new Employee();
Employee emp2 = emp2 = new Employee();
Employee emp3 = emp3 = new Employee();
to
Employee emp1 = new Employee();
Employee emp2 = new Employee();
Employee emp3 = new Employee();
I have tried the given snippet; that works fine for me, please check the properties of the ListBox for it's visibility and also make sure that the Form1_Load event is firing. I have a suggestion to simplify your code by overriding .ToString() in the class in the following way:
public override string ToString()
{
return this.Name + "\t" + this.IdNumber + "\t\t" + this.Department + "\t" + this.Position;
}
So that the code in the Form1_Load will be as like the following:
Employee emp1 = new Employee();
emp1.Name = "Susan Meyers";
emp1.IdNumber = 47899;
emp1.Department = "Accounting";
emp1.Position = "Vice President";
listBox1.Items.Add(emp1.ToString());
Employee emp2 = new Employee();
//init emp2 here
listBox1.Items.Add(emp2.ToString());
Employee emp3 = emp3 = new Employee();
//init emp3 here
listBox1.Items.Add(emp3.ToString());
Related
class EmployeeDAL
{
private ArrayList _employees;
public EmployeeDAL()
{
_employees = new ArrayList();
_employees.Add(new Employee { EmployeeID = 1, EmployeeName = "Ram", Salary = 50000 });
_employees.Add(new Employee { EmployeeID = 2, EmployeeName = "Sahaym", Salary = 40000 });
_employees.Add(new Employee { EmployeeID = 3, EmployeeName = "Gopi", Salary = 55000 });
_employees.Add(new Employee { EmployeeID = 4, EmployeeName = "Prakash", Salary = 45000 });
_employees.Add(new Employee { EmployeeID = 5, EmployeeName = "Dheeraj", Salary = 60000 });
_employees.Add(new Employee { EmployeeID = 6, EmployeeName = "Shibhu", Salary = 50000 });
}
public bool DeleteEmployee(int id)
{
if (_employees.Contains(id))
{
_employees.Remove(id);
return true;
}
else
return false;
}
}
I want to delete an employee with specific id using DeleteEmployee(id) method. How can I do this in ArrayList ?
Hi as an answer to your question you can use the code below :
public bool DeleteEmployee(int id)
{
var employees = _employees.Cast<Employee>()
.Where(e => e.EmployeeID == id)
.Distinct();
if (employees.Count() == 0)
return false;
else
foreach (var employee in employees.ToList())
_employees.Remove(employee);
return true;
}
But in my opinion, if it's possible, you should use another type of collection like a List, it could be easier to handle than an ArrayList.
Forgive the crudeness of my code. But, sample of using a List follows:
using System;
using System.Collections.Generic;
using Gtk;
public partial class MainWindow : Gtk.Window
{
public class Employee
{
public int EmployID;
public string EmployeeName;
public int Salary;
public Employee(int v1, string v2, int v3)
{
this.EmployID = v1;
this.EmployeeName = v2;
this.Salary = v3;
}
}
public class Employees
{
public List<Employee> employees = null;
public bool Delete(int inID)
{
Employee buffer = employees.Find(x => x.EmployID == inID);
if (buffer != null)
{
employees.Remove(buffer);
return true;
}
return false;
}
}
public Employees Listof = new Employees();
public MainWindow() : base(Gtk.WindowType.Toplevel)
{
Build();
Listof.employees = new List<Employee>()
{
new Employee(1, "Ram", 50000),
new Employee(2, "Sahaym", 40000),
new Employee(3, "Gopi", 55000),
new Employee(4, "Prakash", 45000),
new Employee(5, "Dheeraj", 60000),
new Employee(6, "Shibhu", 50000)
};
label1.Text = "Employee Count: " + Listof.employees.Count.ToString();
}
protected void OnDeleteEvent(object sender, DeleteEventArgs a)
{
Application.Quit();
a.RetVal = true;
}
protected void OnButton3Pressed(object sender, EventArgs e)
{
label1.Text = $"Deleted Employee 3 successful : {Listof.Delete(3)}" +
" Employee Count: " + Listof.employees.Count.ToString();
}
This is homework so if you can help thank you, if not I understand.
Everything work as intended. But I feel like I could implement things better or have cleaner code. I would like the button to just call a method that reads the JSON file, runs the inquiry and puts out the correct display without duplicating the code like I have.
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace EmployeePayDataWk4
{
public partial class Employee_Pay_Form : Form
{
public Employee_Pay_Form()
{
InitializeComponent();
}
private void Employee_Pay_Form_Load(object sender, EventArgs e)
{
EmployeeDataGridView.ColumnCount = 8;
EmployeeDataGridView.Columns[0].Name = "Employee Name";
EmployeeDataGridView.Columns[1].Name = "Zip Code";
EmployeeDataGridView.Columns[2].Name = "Age";
EmployeeDataGridView.Columns[3].Name = "Monthly Gross Pay";
EmployeeDataGridView.Columns[4].Name = "Department ID";
EmployeeDataGridView.Columns[5].Name = "Developer Type";
EmployeeDataGridView.Columns[6].Name = "Annual Taxes";
EmployeeDataGridView.Columns[7].Name = "Annual Net Pay";
}
private void LoadAllButton_Click(object sender, EventArgs e)
{
EmployeeDataGridView.Rows.Clear();
//Read from JSON file
string JSONstring = File.ReadAllText("JSON.json");
List<Employee> employees = JsonConvert.DeserializeObject<List<Employee>>(JSONstring);
//Display into DataGridView
foreach (Employee emp in employees)
{
string[] row = { emp.Name, emp.Zip, emp.Age.ToString(), string.Format("{0:C}", emp.Pay),
emp.DepartmentId.ToString(), SetDevType(emp.DepartmentId),
string.Format("{0:C}", emp.CalculateTax(emp.Pay)),
string.Format("{0:C}", AnnualPay(emp.Pay) - emp.CalculateTax(emp.Pay))};
EmployeeDataGridView.Rows.Add(row);
}
}
private void FTEmployeeButton_Click(object sender, EventArgs e)
{
EmployeeDataGridView.Rows.Clear();
//Read from JSON file
string JSONstring = File.ReadAllText("JSON.json");
List<Employee> employees = JsonConvert.DeserializeObject<List<Employee>>(JSONstring);
//LINQ Query for FT Employees
var FTEmp = from emp in employees
where emp.GetTaxForm == "W2"
select emp;
//Display into DataGridView
foreach (Employee emp in FTEmp)
{
string[] row = { emp.Name, emp.Zip, emp.Age.ToString(), string.Format("{0:C}", emp.Pay),
emp.DepartmentId.ToString(), SetDevType(emp.DepartmentId),
string.Format("{0:C}", emp.CalculateTax(emp.Pay)),
string.Format("{0:C}", AnnualPay(emp.Pay) - emp.CalculateTax(emp.Pay))};
EmployeeDataGridView.Rows.Add(row);
}
}
private void ContractEmployeeButton_Click(object sender, EventArgs e)
{
EmployeeDataGridView.Rows.Clear();
//Read from JSON file
string JSONstring = File.ReadAllText("JSON.json");
List<Employee> employees = JsonConvert.DeserializeObject<List<Employee>>(JSONstring);
//LINQ Query for Contract Employees
var contractEmp = from emp in employees
where emp.GetTaxForm == "1099"
select emp;
//Display into DataGridView
foreach (Employee emp in contractEmp)
{
string[] row = { emp.Name, emp.Zip, emp.Age.ToString(), string.Format("{0:C}", emp.Pay),
emp.DepartmentId.ToString(), SetDevType(emp.DepartmentId),
string.Format("{0:C}", emp.CalculateTax(emp.Pay)),
string.Format("{0:C}", AnnualPay(emp.Pay) - emp.CalculateTax(emp.Pay))};
EmployeeDataGridView.Rows.Add(row);
}
}
//Method to determine developer type
string typeName;
public string SetDevType(int id)
{
if (id == 1)
{
typeName = "Object-Oriented";
}
else if (id == 2)
{
typeName = "Scripts";
}
else { typeName = "Unknown"; }
return typeName;
}
public double AnnualPay(double amount) => 12 * amount;
}
class Employee : IFilingStatus
{
public Employee() { }
public string Name { get; set; }
public string Zip { get; set; }
public int Age { get; set; }
public double Pay { get; set; }
public int DepartmentId { get; set; }
public string GetTaxForm { get; set; }
public double CalculateTax(double basis)
{
double monthlyTax;
if ((GetTaxForm == "W2") || (GetTaxForm == "w2"))
{
monthlyTax = .07 * basis;
}
else
{
monthlyTax = 0;
}
return 12 * monthlyTax;
}
public double AnnualPay(double amount) => 12 * amount;
}
public interface IFilingStatus
{
double CalculateTax(double basis);
}
}
I would say this line:
List<Employee> employees = JsonConvert.DeserializeObject<List<Employee>>(JSONstring);
should be
IList<Employee> employees = JsonConvert.DeserializeObject<List<Employee>>(JSONstring);
for this reason.
local variables, private fields and parameters should be lowercase camel case, according to StyleCop:
string jsonString = File.ReadAllText("JSON.json");
The other thing is don't repeat yourself (DRY). These few lines can be refactored to be a separate method:
string JSONstring = File.ReadAllText("JSON.json");
List<Employee> employees = JsonConvert.DeserializeObject<List<Employee>>(JSONstring);
//LINQ Query for Contract Employees
var contractEmp = from emp in employees
where emp.GetTaxForm == "1099"
select emp;
In SetDevType you can totally use switch/case, which performs better.
string typeName; // why do we need this?
private string SetDevType(int id)
{
string typeName = string.Empty;
switch(id){
case 1: typeName = "Something"; break;
default: typeName = "Unknown";
}
return typeName;
}
some members of the class don't need to be public, such as
public double AnnualPay(double amount) => 12 * amount;
can be
private double AnnualPay(double amount) => 12 * amount;
and this method is somehow also in the Employee class, which is a Model class/POCO. POCO classes usually don't contain non-properties (although sometimes ToString and an empty constructor are included).
As I can see your Click event handlers are very similar.
I see only one change:
In your FTEmployeeButton_Click event handler you filter data like that:
var contractEmp = from emp in employees
where emp.GetTaxForm == "1099"
select emp;
And in ContractEmployeeButton_Click event handler you filter data like that:
var FTEmp = from emp in employees
where emp.GetTaxForm == "W2"
select emp;
Other code looks very similar. So we can define your code to one separate method...
But we need understand how filter your data.
For this purpose I suggest to use Tag property of Button class.
In this property you can save any object. In your case you can save GetTaxForm value.
So you can use only one event handler for all your buttons.
Please look next realization:
private void OnButton_Click(object sender, EventArgs e)
{
EmployeeDataGridView.Rows.Clear();
//Read from JSON file
string JSONstring = File.ReadAllText("JSON.json");
List<Employee> employees = JsonConvert.DeserializeObject<List<Employee>>(JSONstring);
object filter = ((Control)sender).Tag;
List<Employee> FTEmp;
if (filter != null) {
//LINQ Query for FT Employees
FTEmp = from emp in employees
where emp.GetTaxForm == filter.ToString()
select emp;
}
else
{
FTEmp = employees.ToList();
}
//Display into DataGridView
foreach (Employee emp in FTEmp)
{
string[] row = { emp.Name, emp.Zip, emp.Age.ToString(), string.Format("{0:C}", emp.Pay),
emp.DepartmentId.ToString(), SetDevType(emp.DepartmentId),
string.Format("{0:C}", emp.CalculateTax(emp.Pay)),
string.Format("{0:C}", AnnualPay(emp.Pay) - emp.CalculateTax(emp.Pay))};
EmployeeDataGridView.Rows.Add(row);
}
}
I've been trying to implement Lucene to make the searching on my website faster.
My code currently works, however, I think I am not correctly making use of Lucene. Right now, my search query is productName:asterisk(input)asterisk - I can't imagine this is what you're supposed to do to find all products where productName contains input. I think it has something to do with the way I save the fields to a document.
My code:
LuceneHelper.cs
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data.Entity.Migrations.Model;
using System.Linq;
using System.Threading.Tasks;
using Lucene.Net;
using Lucene.Net.Analysis;
using Lucene.Net.Analysis.Standard;
using Lucene.Net.Documents;
using Lucene.Net.Index;
using Lucene.Net.QueryParsers;
using Lucene.Net.Search;
using Lucene.Net.Store;
using Rentpro.Models;
using RentPro.Models.Tables;
using RentProModels.Models;
namespace RentPro.Helpers
{
public class LuceneHelper
{
private const Lucene.Net.Util.Version Version = Lucene.Net.Util.Version.LUCENE_30;
private bool IndicesInitialized;
private List<Language> Languages = new List<Language>();
public void BuildIndices(DB db)
{
Languages = GetLanguages(db);
Analyzer analyzer = new StandardAnalyzer(Version);
List<Product> allProducts = db.GetAllProducts(true, false);
foreach (Language l in Languages)
{
BuildIndicesForLanguage(allProducts, analyzer, l.ID);
}
IndicesInitialized = true;
}
private void BuildIndicesForLanguage(List<Product> products, Analyzer analyzer, int id = 0)
{
using (
IndexWriter indexWriter = new IndexWriter(GetDirectory(id), analyzer,
IndexWriter.MaxFieldLength.UNLIMITED))
{
var x = products.Count;
foreach (Product p in products)
{
SearchProduct product = SearchProduct.FromProduct(p, id);
Document document = new Document();
Field productIdField = new Field("productId", product.ID.ToString(), Field.Store.YES, Field.Index.NO);
Field productTitleField = new Field("productName", product.Name, Field.Store.YES, Field.Index.ANALYZED);
Field productDescriptionField = new Field("productDescription", product.Description, Field.Store.YES, Field.Index.ANALYZED);
Field productCategoryField = new Field("productCategory", product.Category, Field.Store.YES, Field.Index.ANALYZED);
Field productCategorySynonymField = new Field("productCategorySynonym", product.CategorySynonym, Field.Store.YES, Field.Index.ANALYZED);
Field productImageUrlField = new Field("productImageUrl", product.ImageUrl, Field.Store.YES, Field.Index.NO);
Field productTypeField = new Field("productType", product.Type, Field.Store.YES, Field.Index.NO);
Field productDescriptionShortField = new Field("productDescriptionShort", product.DescriptionShort, Field.Store.YES, Field.Index.NO);
Field productPriceField = new Field("productPrice", product.Price, Field.Store.YES, Field.Index.NO);
document.Add(productIdField);
document.Add(productTitleField);
document.Add(productDescriptionField);
document.Add(productCategoryField);
document.Add(productCategorySynonymField);
document.Add(productImageUrlField);
document.Add(productTypeField);
document.Add(productDescriptionShortField);
document.Add(productPriceField);
indexWriter.AddDocument(document);
}
indexWriter.Optimize();
indexWriter.Commit();
}
}
public List<SearchProduct> Search(string input)
{
if (!IndicesInitialized)
{
BuildIndices(new DB());
return Search(input);
}
IndexReader reader = IndexReader.Open(GetCurrentDirectory(), true);
Searcher searcher = new IndexSearcher(reader);
Analyzer analyzer = new StandardAnalyzer(Version);
TopScoreDocCollector collector = TopScoreDocCollector.Create(100, true);
MultiFieldQueryParser parser = new MultiFieldQueryParser(Version,
new[] { "productDescription", "productCategory", "productCategorySynonym", "productName" }, analyzer)
{
AllowLeadingWildcard = true
};
searcher.Search(parser.Parse("*" + input + "*"), collector);
ScoreDoc[] hits = collector.TopDocs().ScoreDocs;
List<int> productIds = new List<int>();
List<SearchProduct> results = new List<SearchProduct>();
foreach (ScoreDoc scoreDoc in hits)
{
Document document = searcher.Doc(scoreDoc.Doc);
int productId = int.Parse(document.Get("productId"));
if (!productIds.Contains(productId))
{
productIds.Add(productId);
SearchProduct result = new SearchProduct
{
ID = productId,
Description = document.Get("productDescription"),
Name = document.Get("productName"),
Category = document.Get("productCategory"),
CategorySynonym = document.Get("productCategorySynonym"),
ImageUrl = document.Get("productImageUrl"),
Type = document.Get("productType"),
DescriptionShort = document.Get("productDescriptionShort"),
Price = document.Get("productPrice")
};
results.Add(result);
}
}
reader.Dispose();
searcher.Dispose();
analyzer.Dispose();
return results;
}
private string GetDirectoryPath(int languageId = 1)
{
return GetDirectoryPath(Languages.SingleOrDefault(x => x.ID == languageId).UriPart);
}
private string GetDirectoryPath(string languageUri)
{
return AppDomain.CurrentDomain.BaseDirectory + #"\App_Data\LuceneIndices\" + languageUri;
}
private List<Language> GetLanguages(DB db)
{
return db.Languages.ToList();
}
private int GetCurrentLanguageId()
{
return Translator.GetCurrentLanguageID();
}
private FSDirectory GetCurrentDirectory()
{
return FSDirectory.Open(GetDirectoryPath(GetCurrentLanguageId()));
}
private FSDirectory GetDirectory(int languageId)
{
return FSDirectory.Open(GetDirectoryPath(languageId));
}
}
public class SearchProduct
{
public int ID { get; set; }
public string Description { get; set; }
public string Name { get; set; }
public string ImageUrl { get; set; }
public string Type { get; set; }
public string DescriptionShort { get; set; }
public string Price { get; set; }
public string Category { get; set; }
public string CategorySynonym { get; set; }
public static SearchProduct FromProduct(Product p, int languageId)
{
return new SearchProduct()
{
ID = p.ID,
Description = p.GetText(languageId, ProductLanguageType.Description),
Name = p.GetText(languageId),
ImageUrl =
p.Images.Count > 0
? "/Company/" + Settings.Get("FolderName") + "/Pictures/Products/100x100/" +
p.Images.Single(x => x.Type == "Main").Url
: "",
Type = p is HuurProduct ? "HuurProduct" : "KoopProduct",
DescriptionShort = p.GetText(languageId, ProductLanguageType.DescriptionShort),
Price = p is HuurProduct ? ((HuurProduct)p).CalculatedPrice(1, !Settings.GetBool("BTWExLeading")).ToString("0.00") : "",
Category = p.Category.Name,
CategorySynonym = p.Category.Synonym
};
}
}
}
How I call the LuceneHelper:
public ActionResult Lucene(string SearchString, string SearchOrderBy, int? page, int? amount)
{
List<SearchProduct> searchResults = new List<SearchProduct>();
if (!SearchString.IsNullOrWhiteSpace())
{
LuceneHelper lucene = new LuceneHelper();
searchResults = lucene.Search(SearchString);
}
return View(new LuceneSearchResultsVM(db, SearchString, searchResults, SearchOrderBy, page ?? 1, amount ?? 10));
}
LuceneSearchResultsVM:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic;
using System.Web;
using RentPro.Models.Tables;
using System.Linq.Expressions;
using System.Reflection;
using Microsoft.Ajax.Utilities;
using Rentpro.Models;
using RentPro.Helpers;
using RentProModels.Models;
namespace RentPro.ViewModels
{
public class LuceneSearchResultsVM
{
public List<SearchProduct> SearchProducts { get; set; }
public bool BTWActive { get; set; }
public bool BTWEXInput { get; set; }
public bool BTWShow { get; set; }
public bool BTWExLeading { get; set; }
public string FolderName { get; set; }
public string CurrentSearchString { get; set; }
public string SearchOrderBy { get; set; }
public int Page;
public int Amount;
public String SearchQueryString {
get
{
return Translator.Translate("Zoekresultaten voor") + ": " + CurrentSearchString + " (" +
SearchProducts.Count + " " + Translator.Translate("resultaten") + " - " +
Translator.Translate("pagina") + " " + Page + " " + Translator.Translate("van") + " " +
CalculateAmountOfPages() + ")";
}
set { }
}
public LuceneSearchResultsVM(DB db, string queryString, List<SearchProduct> results, string searchOrderBy, int page, int amt)
{
BTWActive = Settings.GetBool("BTWActive");
BTWEXInput = Settings.GetBool("BTWEXInput");
BTWShow = Settings.GetBool("BTWShow");
BTWExLeading = Settings.GetBool("BTWExLeading");
FolderName = Settings.Get("FolderName");
SearchProducts = results;
CurrentSearchString = queryString;
if (searchOrderBy.IsNullOrWhiteSpace())
{
searchOrderBy = "Name";
}
SearchOrderBy = searchOrderBy;
Amount = amt == 0 ? 10 : amt;
int maxPages = CalculateAmountOfPages();
Page = page > maxPages ? maxPages : page;
SearchLog.MakeEntry(queryString, SearchProducts.Count(), db, HttpContext.Current.Request.UserHostAddress);
}
public List<SearchProduct> GetOrderedList()
{
List<SearchProduct> copySearchProductList = new List<SearchProduct>(SearchProducts);
copySearchProductList = copySearchProductList.Skip((Page - 1) * Amount).Take(Amount).ToList();
switch (SearchOrderBy)
{
case "Price":
copySearchProductList.Sort(new PriceSorter());
break;
case "DateCreated":
return copySearchProductList; //TODO
default:
return copySearchProductList.OrderBy(n => n.Name).ToList();
}
return copySearchProductList;
}
public int CalculateAmountOfPages()
{
int items = SearchProducts.Count;
return items / Amount + (items % Amount > 0 ? 1 : 0);
}
}
public class PriceSorter : IComparer<SearchProduct>
{
public int Compare(SearchProduct x, SearchProduct y)
{
if (x == null || x.Price == "") return 1;
if (y == null || y.Price == "") return -1;
decimal priceX = decimal.Parse(x.Price);
decimal priceY = decimal.Parse(y.Price);
return priceX > priceY ? 1 : priceX == priceY ? 0 : -1;
}
}
}
Any help would be greatly appreciated.
Example input list of products:
Query:
SELECT Product.ID, Product.Decription, Product.Name FROM Product
Desired results:
SQL Server query equivalent:
SELECT Product.ID, Product.Decription, Product.Name FROM Product WHERE Product.Name LIKE '%Zelf%' OR Product.Decription LIKE '%Zelf%'
Basically, Zelf is the input. I want to find all matches with product descriptions or product names that contain the input string.
ucene not allows to use ? or * as starting symbols of the searching term. To overcome this issue you need to store in your index a sub-strings from any position of word to it end position. E.g. for word test you should put to index
test
est
st
t
I recommend to use separate field for that. Java example for case if you have a short field with one word like a product name.
for(int i = 0; i < product.SafeName.length()-1; i++){
Field productTitleSearchField = new Field("productNameSearch", product.SafeName.substring(i, product.SafeName.length()), Field.Store.NO, Field.Index.ANALYZED);
}
After this you can use following query string
productNameSearch:(input)asterisk or use a PrefixQuery for searching product names containing input.
In case if you have several words in you field and for you will be enough to have some reasonable length of your input, then it will better to add for this field a NGramTokenFilter. You if have limit on your input string from n to m you should create a NGram Token Filter with n minGram and m maxGramm. If you has word test and you limit 2 to 3 you will have in your index words
te
tes
es
est
st
After this you can search via string
ngrammField:(input)
This doesn't answer your question but it is safer to use the using block in C#. In your current code, calling dispose can throw.
You're doing:
IndexReader reader = IndexReader.Open(GetCurrentDirectory(), true);
Searcher searcher = new IndexSearcher(reader);
Analyzer analyzer = new StandardAnalyzer(Version);
//...
reader.Dispose();
searcher.Dispose();
analyzer.Dispose();
Which can be replaced with:
using (IndexReader reader = IndexReader.Open(GetCurrentDirectory(), true))
using (Searcher searcher = new IndexSearcher(reader))
using (Analyzer analyzer = new StandardAnalyzer(Version))
{
//Do whatever else here.. No need to call "dispose".
}
The above is pretty much a try -> finally statement where it tries to do whatever is in the using statement. If anything throws, the finally block disposes the resources opened/allocated.
Another way (comma operator.. if all variables are of the same type) is:
using (whatever foo = new whatever(), whatever bar = new whatever(), ...)
{
//do whatever here..
}
As i said in the title the query that i written retun nothing while the same tried in Valentina Studio to check the database work fine and i don't understand whats wrong.
Here the code:
using System;
using System.Collections.Generic;
using System.Text;
using SQLite;
namespace SQLite_Analizer
{
public class sqlite_master
{
public string name { get; set; }
}
public class manager
{
public List<string> GetListTables(string DBName)
{
List<string> tablesList = new List<string>();
string itemName = null;
var con = new SQLiteAsyncConnection(DBName);
var query = con.QueryAsync<sqlite_master>("SELECT name FROM sqlite_master WHERE type='table' AND NOT SUBSTR(name,1,6) = 'sqlite' ORDER BY name").GetAwaiter().GetResult();
foreach(var tablesItem in query)
{
itemName = "\n" + tablesItem.name + "\n\n";
tablesList.Add(itemName);
}
return tablesList;
}
}
}
Here the new code with a counter to check query result number.
using System;
using System.Collections.Generic;
using System.Text;
using SQLite;
namespace SQLite_Analizer
{
public class sqlite_master
{
public string name { get; set; }
}
public class manager
{
private List<string> tablesList;
private int count;
public manager()
{
tablesList = new List<string>();
count = 0;
}
public List<string> getList()
{
return tablesList;
}
public int getCount()
{
return count;
}
public async void GetListTables(string DBName)
{
string itemName = null;
var con = new SQLiteAsyncConnection(DBName);
var query = await con.QueryAsync<sqlite_master>("SELECT name FROM sqlite_master WHERE type='table' AND NOT SUBSTR(name,1,6) = 'sqlite' ORDER BY name");
foreach (var tablesItem in query)
{
itemName = "\n" + tablesItem.name + "\n\n";
tablesList.Add(itemName);
}
count = query.Count;
}
}
}
I would try something like this
public async List<string> GetListTables(string DBName)
{
List<string> tablesList = new List<string>();
string itemName = null;
var con = new SQLiteAsyncConnection(DBName);
var query = await con.QueryAsync<sqlite_master>("SELECT name FROM sqlite_master WHERE type='table' AND NOT SUBSTR(name,1,6) = 'sqlite' ORDER BY name");
foreach(var tablesItem in query)
{
itemName = "\n" + tablesItem.name + "\n\n";
tablesList.Add(itemName);
}
return tablesList;
}
Im a beginner at programming using C#, and my lecturer has given us a tricky project.
I've managed to complete all of it except... arrays!
Long story short, I've got 5 textboxes all of which take input from the user. This information is to be stored into an array and then listed in order (date of birth order) displaying in a rich text box, I've listed the code I've managed to do below:
private void button2_Click(object sender, EventArgs e)
{
{
bc[0] = new Student();
bc[1] = new Student(Convert.ToInt32(textBox1.Text), "Mary", "Ford");
bc[2] = new Student(1254, "Andrew", "White");
bc[3] = new Student(1256, "Liam", "Sharp", " ");
bc[4] = new Student(1266, "Michael", "Brown", " ");
for (int i = 0; i < 5; i++)
{
string bcString = bc[i].studentToString() + "\r\n";
richTextBox1.AppendText(bcString);
}
}
}
CLASS "Student":
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Assignment_2
{
class Student
{
private int accountNum;
private string firstName;
private string lastName;
private string balance;
// first constructor
public Student()
{
accountNum = 0;
firstName = "";
lastName = "";
balance = "";
}
// second constructor
public Student(int accValue, string firstNameVal, string lastNameVal)
{
accountNum = accValue;
firstName = firstNameVal;
lastName = lastNameVal;
balance = "";
}
// third constructor
public Student(int accValue, string firstNameVal,
string lastNameVal, string balanceValue)
{
accountNum = accValue;
firstName = firstNameVal;
lastName = lastNameVal;
balance = balanceValue;
}
public int AccountNum
{
get
{
return accountNum;
}
set
{
accountNum = value;
}
}
public string FirstName
{
get
{
return firstName;
}
set
{
firstName = value;
}
}
public string studentToString()
{
return (Convert.ToString(accountNum) + " " + firstName +
" " + lastName + " " + balance);
}
}
}
Make your class Student implement the IComparable interface, then sort for the field DateOfBirth (if it exists). This example works on the AccountNum but should be trivial to change with a DateOfBirth
Student[] bc = new Student[5];
bc[0] = new Student();
bc[1] = new Student(9999, "Mary", "Ford");
bc[2] = new Student(1254, "Andrew", "White");
bc[3] = new Student(1256, "Liam", "Sharp", " ");
bc[4] = new Student(1266, "Michael", "Brown", " ");
// Here the sort on the AccountNum
Array.Sort(bc);
// A StringBuilder instead of the RichTextBox for testing....
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 5; i++)
{
string bcString = bc[i].studentToString() + "\r\n";
sb.Append(bcString);
}
Console.WriteLine(sb.ToString());
CLASS STUDENT: (Just the part for the IComparable)
class Student : IComparable
{
.....
public int CompareTo(object obj)
{
if (obj == null) return 1;
Student otherStudent = obj as Student;
if (otherStudent != null)
return this.accountNum.CompareTo(otherStudent.AccountNum);
else
throw new ArgumentException("Object is not a Student");
}
....
}