How to parse text file and connect to database in C#? - c#
I'm trying to parse the text file but unable to parse the contents under "Columns:", "Records:", "Relationships:" headings.
My text file format:
Database
Type: SQL Server
Connection String:Server=localhost\SQLEXPRESS;Database=master;Trusted_Connection=True;
DBName:FirstDataBase
Tables
Table
Name:TableName1
Columns:
ID,numeric,4
Name,name,20
Designation,varchar,20
Relationships:
Records:
9001,XYZ,Director
8038,MNO,Associate
9876,LOP,HR
Table
Name:TableName2
Columns:
ID,numeric,4
Name,name,20
Designation,varchar,20
Relationships:
TableName1,TableName2,FK,ID
Records:
8038,MNO,Associate
My C# code:
static void Main(string[] args)
{
Console.WriteLine("Enter file name");
string filep = Console.ReadLine();
string filePath = $"C:\\Files\\{filep}.txt";
List<Columns> col = new List<Columns>();
List<TableName> tn = new List<TableName>();
string[] lines = File.ReadAllLines(filePath);
foreach (var line in lines)
{
if (line.StartsWith("\t" + "\t" + "Name:"))
{
TableName newTN = new TableName();
string s = line.Split(':')[1];
newTN.TName = s;
tn.Add(newTN);
Console.WriteLine(s);
}
if (line.StartsWith("\t" + "\t" + "Columns:"))
{
// Here I'm stuck
}
}
}
One of my model classes:
public class Columns
{
public string CName { get; set; }
public string CType { get; set; }
public string CSize { get; set; }
public string Ckey { get; set; }
}
I've tried various codes but still, I'm unable to parse it. Solutions are welcome and thanks in advance.
I'm stuck at how to make the program read the next lines of particular heading and store it in a list. If it is solved then I can easily make queries and connect to the database.
Try following :
sing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ConsoleApp1
{
class Program
{
const string FILENAME = #"c:\temp\test.txt";
static void Main(string[] args)
{
Database database = new Database(FILENAME);
}
}
public enum STATE
{
GET_DATABASE,
GET_TABLES
}
public enum TABLE_FIELD
{
NONE,
NAME,
COLUMNS,
RELATIONSHIPS,
RECORDS
}
public class Database
{
public string type { get; set; }
public string connection { get; set; }
public string name { get; set; }
public List<Table> tables { get; set; }
public Database(string filename)
{
StreamReader reader = new StreamReader(filename);
string line = "";
STATE state = STATE.GET_DATABASE;
TABLE_FIELD tableField = TABLE_FIELD.NONE;
Table table = null;
string[] splitLine;
while((line = reader.ReadLine()) != null)
{
line = line.Trim();
if (line.Length > 0)
{
switch (state)
{
case STATE.GET_DATABASE:
if (line == "Tables")
{
state = STATE.GET_TABLES;
}
else
{
if (line.Contains(":"))
{
splitLine = line.Split(new char[] { ':' });
switch (splitLine[0])
{
case "Type":
type = splitLine[1].Trim();
break;
case "Connection String":
connection = splitLine[1].Trim();
break;
case "DBName":
name = splitLine[1].Trim();
break;
}
}
}
break;
case STATE.GET_TABLES:
if(line == "Table")
{
if (tables == null) tables = new List<Table>();
table = new Table();
tables.Add(table);
}
else
{
if (line.Contains(":"))
{
splitLine = line.Split(new char[] { ':' });
switch (splitLine[0])
{
case "Name":
table.name = splitLine[1].Trim();
tableField = TABLE_FIELD.NAME;
break;
case "Columns":
connection = splitLine[1].Trim();
tableField = TABLE_FIELD.COLUMNS;
break;
case "Relationships":
name = splitLine[1].Trim();
tableField = TABLE_FIELD.RELATIONSHIPS;
break;
case "Records":
name = splitLine[1].Trim();
tableField = TABLE_FIELD.RECORDS;
break;
}
}
else
{
switch (tableField)
{
case TABLE_FIELD.COLUMNS:
if (table.columns == null) table.columns = new List<Column>();
Column column = new Column();
table.columns.Add(column);
splitLine = line.Split(new char[] { ',' });
column.name = splitLine[0];
column.type = (COLUMN_TYPE)Enum.Parse(typeof(COLUMN_TYPE), splitLine[1]);
column.length = int.Parse(splitLine[2]);
break;
case TABLE_FIELD.RECORDS:
splitLine = line.Split(new char[] { ',' });
if (table.records == null) table.records = new List<List<object>>();
List<object> row = new List<object>();
table.records.Add(row);
for(int i = 0; i < splitLine.Length; i++)
{
switch(table.columns[i].type)
{
case COLUMN_TYPE.numeric:
row.Add(int.Parse(splitLine[i]));
break;
case COLUMN_TYPE.name:
row.Add(splitLine[i]);
break;
case COLUMN_TYPE.varchar:
row.Add(splitLine[i]);
break;
}
}
break;
default:
break;
}
}
}
break;
}
}
}
}
}
public class Table
{
public string name { get; set; }
public List<Column> columns { get; set; }
public List<Relationship> relationships { get; set; }
public List<List<object>> records { get; set; }
}
public enum COLUMN_TYPE
{
numeric,
name,
varchar
}
public class Column
{
public string name { get; set; }
public COLUMN_TYPE type { get; set; }
public int length { get; set; }
}
public class Relationship
{
}
}
Related
How to write commands for File/Json
Below is the code I made but I don't know where to start. I will be grateful for the hint. I have no idea what i should do next.. I want to make a program that will have a few commands. Adding a new planet Planet Removal Show the List Save to JSON displays planet data public class MyDate { public int masa { get; set; } public int sredni { get; set; } } public class Lad { public string PlanetName { get; set; } public MyDate Szczegoly { get; set; } } class Program { static void Main() { string choice = Console.ReadLine(); //string choiceup = choice.ToUpper(); switch (choice) { case "Add": Add(); return; case "Save": break; case "List": LoadList(); break; case "Exit": return; } } public static void Add() { Console.WriteLine("Podaj nazwe planety"); string name = Console.ReadLine(); Console.WriteLine("Podaj mase"); int masa = Convert.ToInt16(Console.ReadLine()); Console.WriteLine("Podaj srednice"); int sred = Convert.ToInt16(Console.ReadLine()); List<Lad> _data = new List<Lad>(); _data.Add(new Lad() { PlanetName = name, Szczegoly = new MyDate { masa = masa, sredni = sred } }); var json = System.Text.Json.JsonSerializer.Serialize(_data); Console.WriteLine(json); string json2 = JsonConvert.SerializeObject(_data, Formatting.Indented); File.AppendAllText(#"tescikkk.json", json2); } static List<Lad> LoadList() { string text = File.ReadAllText(#"tescikkk.json"); if (string.IsNullOrEmpty(text)) return new List<Lad>() { }; return JsonConvert.DeserializeObject<Lad[]>(text).ToList(); } }
How to parse INI file?
I have ini files that contains data from server. Map.ini [MAP_1] MapType = 1 MapWar = 1 Position = 42.03,738.2,737.3 [MAP_2] MapType = 1 MapWar = 1 Position = 42.03,738.2,737.3 How to read map.ini that contains this kind of files and save it in Dictionary or List.
Try following : using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace ConsoleApplication1 { class Program { const string FILENAME = #"c:\temp\test.txt"; static void Main(string[] args) { List<Map> maps = new List<Map>(); Map map = null; StreamReader reader = new StreamReader(FILENAME); string line = ""; while ((line = reader.ReadLine()) != null) { line.Trim(); if (line.Length > 0) { if(line.StartsWith("[")) { string name = line.Trim(new char[] { '[', ']' }); map = new Map(); maps.Add(map); map.name = name; } else { string[] data = line.Split(new char[] { '=' }); switch (data[0].Trim()) { case "MapType" : map.mapType = int.Parse(data[1]); break; case "MapWar": map.mapWar = int.Parse(data[1]); break; case "Position": string[] numbers = data[1].Split(new char[] { ',' }); map.x = decimal.Parse(numbers[0]); map.y = decimal.Parse(numbers[1]); map.z = decimal.Parse(numbers[2]); break; default : break; } } } } Dictionary<string, Map> dict = maps .GroupBy(x => x.name, y => y) .ToDictionary(x => x.Key, y => y.FirstOrDefault()); } } public class Map { public string name { get; set; } public int mapType { get; set; } public int mapWar { get; set; } public decimal x { get; set; } public decimal y { get; set; } public decimal z { get; set; } } }
Parsing A Complex, Multiline CSV File in C#
I have searched the site, and found multiple examples for how to accomplish C# parsing using a variety of methods...but have found none that can help me in this specific scenario. I have a complex CSV file that needs parsing. Here is a sampling of some of the header data... REPORT TITLE,New Query,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, REPORT DESCRIPTION,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, GENERATED,12/20/2019 7:33 AM ET,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, Client Name,Client A,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, Time Frame,Last Completed Period,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, ,Calendar year,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, Received Date,Custom,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, ,01/01/2015 - 12/31/2015,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, Service Date,Custom,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, ,01/01/2015 - 12/31/2015,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, Adjustments,CHOICE(S),,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, ,Phone Calibration,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, View,N/A,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, SERVICE LINE,Service Line Example A,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, SITE,General 1,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, ,General 2,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, ,General 3,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, ,General 4,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, ,General 5,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, ,General 7,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, FILTER,CHOICE(S),,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, Client ID,'00001',,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, ,'00002',,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, ,'00003',,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, ,'00004',,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, ,'00005',,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, ,'00006',,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, There is NOTHING I can do about the formatting of the CSV file, as it is part of a legacy system. The 40 commas placed at the end of each row, as well as those used as row separators, are placed by the system. Here is where I am with my code so far... using System; using System.Collections.Generic; using System.IO; using System.Linq; using Microsoft.VisualBasic.FileIO; using System.Text.RegularExpressions; namespace ConsoleUI { class Program { static void Main(string[] args) { var sourcePath = #"L:\sourceData.csv"; var delimiter = ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,"; var tempPath = Path.GetTempFileName(); var lineNumber = 0; var splitExpression = new Regex(#"(" + delimiter + #")(,)(?=(?:[^""]|""[^""]*"")*$)"); using (var writer = new StreamWriter(tempPath)) using (var reader = new StreamReader(sourcePath)) { string line = null; while ((line = reader.ReadLine()) != null) { lineNumber++; var rows = splitExpression.Split(line).Where(s => s != delimiter).ToArray(); // This is where I need to place the parsed data into objects writer.WriteLine(string.Join(delimiter, rows)); } } } } } Ultimately, I need to move each parsed piece of data into its own defined object. I have that class already built. ANY help that can be provided would be considered a holiday miracle at this point! Thanks for your time.
try following : using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace ConsoleApplication1 { class Program { const string FILENAME = #"c:\temp\test.csv"; static void Main(string[] args) { StreamReader reader = new StreamReader(FILENAME); string line = ""; Report report = new Report(); string header = ""; while ((line = reader.ReadLine()) != null) { List<string> data = new List<string>(); string[] row = line.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToArray(); if (row.Length > 0) { if (line.StartsWith(",")) { data = row.ToList(); } else { header = row[0]; data = row.Skip(1).ToList(); } if (data.Count == 0) continue; switch (header) { case "REPORT TITLE": report.title = data[0]; break; case "REPORT DESCRIPTION": report.description = data[0]; break; case "GENERATED": report.generated = data[0]; break; case "Client Name": report.name = data[0]; break; case "Time Frame": if (report.timeFrame == null) report.timeFrame = new List<string>(); report.timeFrame.AddRange(data); break; case "Received Date": if (report.receivedDate == null) report.receivedDate = new List<string>(); report.receivedDate.AddRange(data); break; case "Service Date": if (report.serviceDate == null) report.serviceDate = new List<string>(); report.serviceDate.AddRange(data); break; case "Adjustments": if (report.adjustments == null) report.adjustments = new List<string>(); report.adjustments.AddRange(data); break; case "View": if (report.view == null) report.view = new List<string>(); report.view.AddRange(data); break; case "SERVICE LINE": if (report.serviceLine == null) report.serviceLine = new List<string>(); report.serviceLine.AddRange(data); break; case "SITE": if (report.site == null) report.site = new List<string>(); report.site.AddRange(data); break; case "FILTER": if (report.filter == null) report.filter = new List<string>(); report.filter.AddRange(data); break; case "Client ID": if (report.clientId == null) report.clientId = new List<string>(); report.clientId.AddRange(data); break; } } } } } public class Report { public string title { get; set; } public string description { get; set; } public string generated { get; set; } public string name { get; set; } public List<string> timeFrame { get; set; } public List<string> receivedDate { get; set; } public List<string> serviceDate { get; set; } public List<string> adjustments { get; set; } public List<string> view { get; set; } public List<string> serviceLine { get; set; } public List<string> site { get; set; } public List<string> filter { get; set; } public List<string> clientId { get; set; } } }
Composite join on two CSV files in C#
Starting from a table of daily fruit prices fruits.csv Day,Name,Kind,Price 2019-09-04,"apple","red",63.09 2019-09-04,"apple","yellow",52.14 2019-09-04,"orange","navel",41.18 2019-09-04,"orange","blood",41.18 2019-09-03,"apple","red",63.07 2019-09-03,"apple","yellow",52.11 2019-09-03,"orange","navel",41.13 2019-09-03,"orange","blood",41.13 I'd like to insert the reference prices by name and kind fruit_ref_prices.csv Name,Kind,Reference_Price "apple","red",60.00 "apple","yellow",50.00 "orange","navel",40.00 "orange","blood",42.00 to result in the following table Day,Name,Kind,Price,Reference_Price 2019-09-04,"apple","red",63.09,60.00 2019-09-04,"apple","yellow",52.14,50.00 2019-09-04,"orange","navel",41.18,40.00 2019-09-04,"orange","blood",41.18,42.00 2019-09-03,"apple","red",63.07,60.00 2019-09-03,"apple","yellow",52.11,50.00 2019-09-03,"orange","navel",41.13,40.00 2019-09-03,"orange","blood",41.13,42.00 The solution should be simple using C#'s built-in SQL-like syntax, and I'm sure the answer lies in one of the following tutorial pages: Join clause Perform custom join operations Join by using composite keys but I'm having a hard time identifying the syntax of this language. In my attempt below instead of writing join fruit_ref in fruit_refs on fruit.name equals fruit_ref.name I should be able to write join fruit_ref in fruit_refs on fruit.name equals fruit_ref.name and fruit.kind equals fruit_ref.kind but the Boolean expression is not accepted. Why? My attempt is: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using System.IO; namespace MyConsoleApplication { class Program { const string root = #"c:\path\to\here\"; const string file1_in = root + #"fruits.csv"; const string file2_in = root + #"fruit_ref_prices.csv"; static void Main(string[] args) { Fruit_Basket fruit_basket = new Fruit_Basket(file1_in, file2_in); fruit_basket.PrintFruits(); } } public class Fruit { public DateTime day { get; set; } public string name { get; set; } public string kind { get; set; } public decimal price { get; set; } public Fruit(DateTime newFruit_day, string newFruit_name, string newFruit_kind, decimal newFruit_price) { this.day = newFruit_day; this.name = newFruit_name; this.kind = newFruit_kind; this.price = newFruit_price; } } public class Fruit_Ref { public string name; public string kind; public decimal reference_price; public Fruit_Ref(string newName, string newKind, decimal newRef_Price) { this.name = newName; this.kind = newKind; this.reference_price = newRef_Price; } } public class Fruit_Basket { public List<Fruit> fruits { get; set; } public List<Fruit_Ref> fruit_refs { get; set; } public Fruit_Basket(string file1_in, string file2_in) { build_fruit_list(file1_in); build_fruit_ref_list(file2_in); } public void build_fruit_list(string file_in) { fruits = new List<Fruit>(); int count = 0; StreamReader reader = new StreamReader(file_in); string line = ""; while ((line = reader.ReadLine()) != null) { if (++count > 1) { string[] splitLine = line.Split(new char[] { ',' }).ToArray(); var newFruit_day = DateTime.Parse(splitLine[0]); var newFruit_name = splitLine[1]; var newFruit_kind = splitLine[2]; var newFruit_price = decimal.Parse(splitLine[3]); Fruit newFruit = new Fruit(newFruit_day, newFruit_name, newFruit_kind, newFruit_price); fruits.Add(newFruit); } } reader.Close(); } public void build_fruit_ref_list(string file_in) { fruit_refs = new List<Fruit_Ref>(); int count = 0; StreamReader reader = new StreamReader(file_in); string line = ""; while ((line = reader.ReadLine()) != null) { if (++count > 1) { string[] splitLine = line.Split(new char[] { ',' }).ToArray(); var newFruit_name = splitLine[0]; var newFruit_kind = splitLine[1]; var newFruit_ref_price = decimal.Parse(splitLine[2]); Fruit_Ref newFruit_ref = new Fruit_Ref(newFruit_name, newFruit_kind, newFruit_ref_price); fruit_refs.Add(newFruit_ref); } } reader.Close(); } public void PrintFruits() { var innerJoinQuery = from fruit in fruits join fruit_ref in fruit_refs on fruit.name equals fruit_ref.name select new { Day = fruit.day, Name = fruit.name, Kind = fruit.kind, Price = fruit.price, Reference_Price = fruit_ref.reference_price }; Console.WriteLine($#"""Date"",""Name"",""Kind"",""Price"",""Ref Price"""); foreach (var i in innerJoinQuery) { Console.WriteLine($#"{i.Day},{i.Kind},{i.Price},{i.Reference_Price}"); } } } }
You could also refactor your code to use the CsvHelper NuGet package for reading/writing CSV files. First, You can make these classes to reflect the fruits, fruit references and final fruit structure. public class Fruit { public string Day { get; set; } public string Name { get; set; } public string Kind { get; set; } public string Price { get; set; } } public class FruitReferencePrice { public string Name { get; set; } public string Kind { get; set; } public string Reference_Price { get; set; } } public class FruitFinal { public string Day { get; set; } public string Name { get; set; } public string Kind { get; set; } public string Price { get; set; } public string ReferencePrice { get; set; } public override string ToString() { return $"Day={Day},Name={Name},Kind={Kind},Price={Price},Reference_Price={ReferencePrice}"; } } Then you can make two methods to return the rows of each CSV file into List<Fruit> and List<FruitReferencePrice>. private static IEnumerable<Fruit> BuildFruitList(string csvFilePath) { if (!File.Exists(csvFilePath)) { throw new FileNotFoundException("Could not locate CSV at path " + csvFilePath, csvFilePath); } try { using var fileReader = File.OpenText(csvFilePath); using var csv = new CsvReader(fileReader); return csv.GetRecords<Fruit>().ToList(); } catch (Exception ex) { Console.WriteLine(ex.Message); return Enumerable.Empty<Fruit>(); } } private static IEnumerable<FruitReferencePrice> BuildFruitReferenceList(string csvFilePath) { if (!File.Exists(csvFilePath)) { throw new FileNotFoundException("Could not locate CSV at path " + csvFilePath, csvFilePath); } try { using var fileReader = File.OpenText(csvFilePath); using var csv = new CsvReader(fileReader); return csv.GetRecords<FruitReferencePrice>().ToList(); } catch (Exception ex) { Console.WriteLine(ex.Message); return Enumerable.Empty<FruitReferencePrice>(); } } Then you can perform a grouped join and output the merged result. var path1 = "PATH\\fruits.csv"; var path2 = "PATH\\fruit_ref_prices.csv"; var fruitList = BuildFruitList(path1); var fruitReferencePrices = BuildFruitReferenceList(path2); var groupedJoin = from fruit in fruitList join fruit_ref in fruitReferencePrices on new { fruit.Name, fruit.Kind } equals new { fruit_ref.Name, fruit_ref.Kind } select new FruitFinal { Day = fruit.Day, Name = fruit.Name, Kind = fruit.Kind, Price = fruit.Price, ReferencePrice = fruit_ref.Reference_Price }; foreach (var fruit in groupedJoin) { Console.WriteLine(fruit.ToString()); } Merged results: Day=2019-09-04,Name=apple,Kind=red,Price=63.09,Reference_Price=60.00 Day=2019-09-04,Name=apple,Kind=yellow,Price=52.14,Reference_Price=50.00 Day=2019-09-04,Name=orange,Kind=navel,Price=41.18,Reference_Price=40.00 Day=2019-09-04,Name=orange,Kind=blood,Price=41.18,Reference_Price=42.00 Day=2019-09-03,Name=apple,Kind=red,Price=63.07,Reference_Price=60.00 Day=2019-09-03,Name=apple,Kind=yellow,Price=52.11,Reference_Price=50.00 Day=2019-09-03,Name=orange,Kind=navel,Price=41.13,Reference_Price=40.00 Day=2019-09-03,Name=orange,Kind=blood,Price=41.13,Reference_Price=42.00
Please change the equals clause as on new { fruit.name, fruit.kind } equals new { fruit_ref.name, fruit_ref.kind } Why you require this The query has two anonymous types (one for left table and one for right table). So to compare those anonymous types, the linq statement should use new keyword Query : var innerJoinQuery = from fruit in fruits join fruit_ref in fruit_refs on new { fruit.name, fruit.kind } equals new { fruit_ref.name, fruit_ref.kind } select new { Day = fruit.day, Name = fruit.name, Kind = fruit.kind, Price = fruit.price, Reference_Price = fruit_ref.reference_price };
how to create my custom control C#?
i try to write my own control.But my control' html has problem: Look like My Search button look above. But i need below: how can i do that? using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web.UI.WebControls.WebParts; // Ekle using System.Web.UI.WebControls; // Ekle using System.Web.UI; using System.Collections; using System.Threading; namespace MyFilterControl { public class FilterControl : WebPart { internal List<Content> list { get; set; } public Button BtnSearch { get; set; } public event EventHandler Click; public string FilterButtonText { get; set; } public String PhID { get; set; } internal PlaceHolder PlhControl { get; set; } private string controlWidth = "10"; public FilterControl() { list = new List<Content>(); BtnSearch = new Button(); PlhControl = new PlaceHolder(); PlhControl.ID = Guid.NewGuid().ToString(); if (string.IsNullOrEmpty(PhID)) { BtnSearch.ID = "btnSearch"; } else BtnSearch.ID = PhID; if (string.IsNullOrEmpty(FilterButtonText)) { BtnSearch.Text = "Search"; } else BtnSearch.Text = FilterButtonText; BtnSearch.Click += new EventHandler(BtnSearch_Click); } private Table mainTable = new Table(); protected override void CreateChildControls() { base.CreateChildControls(); TableRow tblRow = new TableRow(); TableCell tblCell1 = new TableCell(); PlhControl.Controls.Add(new LiteralControl("<table><tr>")); tblCell1.Controls.Add(PlhControl); TableCell tblCell2 = new TableCell(); tblCell2.Controls.Add(BtnSearch); tblRow.Cells.Add(tblCell1); tblRow.Cells.Add(tblCell2); mainTable.Rows.Add(tblRow); this.Controls.Add(mainTable); } void BtnSearch_Click(object sender, EventArgs e) { PlhControl.Controls.Add(new LiteralControl("</tr><table>")); foreach (var item in PlhControl.Controls) { if (item is MyTextBoxControl) { MyTextBoxControl t1 = (MyTextBoxControl)item; if (t1.Text != "") { Add(new Content() { FieldName = t1.ID, Data = t1.Text, ID = Guid.NewGuid().ToString(), dataType = t1.dataType, filter=t1.filter }); } } } Click(this, e); } public string Query() { string Qry = String.Empty; int i = 0; foreach (var item in list) { switch (item.filter) { case Filter.BeginsWith: Qry += String.Format(item.FieldName.ToString() + ".StartsWith({0}) && ", "#" + i.ToString()); break; case Filter.EndsWith: Qry += String.Format(item.FieldName.ToString() + ".EndsWith({0}) && ", "#" + i.ToString()); break; case Filter.Contains: Qry += String.Format(item.FieldName.ToString() + ".Contains({0}) && ", "#"+i.ToString()); break; case Filter.Default: Qry += String.Format("{0}=={1} && ", item.FieldName, "#" + i.ToString()); break; default: break; } i++; } Qry = Qry.TrimEnd('&', '&', ' '); return Qry; } public object[] QueryParams() { ArrayList arrList = new ArrayList(); foreach (var item in list) { if (item.dataType == DataType.String) arrList.Add(item.Data); else if (item.dataType == DataType.Int32) { int intVal = Convert.ToInt32(item.Data); arrList.Add(intVal); } } object[] strArray = arrList.ToArray(typeof(object)) as object[]; return strArray; } public string id { get; set; } public void AddItem(ContentItem content) { PlhControl.Controls.Add(new LiteralControl("<td style=\"text-align:left\">")); PlhControl.Controls.Add(new Label() { ID = Guid.NewGuid().ToString(), Text = content.LabelName }); PlhControl.Controls.Add(new LiteralControl(":</td>")); PlhControl.Controls.Add(new LiteralControl("<td style=\"text-align:left\">")); PlhControl.Controls.Add(new MyTextBoxControl() { ID = content.FieldName, dataType = content.dataType, filter = content.filter }); PlhControl.Controls.Add(new LiteralControl("</td>")); } private void Add(Content content) { list.Add(new Content() { ID = content.ID, Data = content.Data, FieldName = content.FieldName, dataType=content.dataType, filter= content.filter }); } } internal class Content { internal string ID { get; set; } public string Data { get; set; } public string FieldName { get; set; } public DataType dataType { get; set; } public Filter filter { get; set; } } public class ContentItem { private string ID { get; set; } public string LabelName { get; set; } public string FieldName { get; set; } public DataType dataType { get; set; } public Filter filter { get; set; } } public class MyTextBoxControl : TextBox { public DataType dataType { get; set; } public Filter filter { get; set; } } public enum DataType { String,Int32 } public enum Filter { BeginsWith,EndsWith,Contains,Default } }
You can place each control in a table cell. Or you can place everything in a div with a fixed heigh.