I have this price range, formed in a string like this:
100:105 , 110:120 , 150:200 , 240:245
This means the prices range from
100 to 105
and
110 to 120
and
150 to 200
and
240 to 245
I want to check if a new price range is within our acceptable price range. Here is my code so far:
int ibegin = 110
int iend = 115
string BeginEnd = "100:105,110:120,150:200,240:245";
string[] strBeginEnd = BeginEnd.Split(',');
int pos = Array.IndexOf(strBeginEnd, ibegin+":"+ iend);
if (pos > -1)
{
RepText = RepText + ScriptBefore + TextIn + ScriptAfter + TextAfter;
}
This code works if the price start and end matches the start and end of the range.
For example, if ibegin = 110 and iend = 120 then my code will find it based on if 110:120 exists in the list.
However, if the iend = 115 it won't find it.
public static void Main(string[] args) {
string BeginEnd = "100:105,110:120,150:200,240:245";
Dictionary<string, int[]> data = new Dictionary<string, int[]>();
foreach (var val in BeginEnd.Split(",")) {
var start = int.Parse(val.Split(":")[0]);
var end = int.Parse(val.Split(":")[1]);
var range = new int[end - start+1];
for (var i = 0; i < range.Length; i++) {
range[i] = start + i;
}
data.Add(val, range);
}
var test1 = check(110);
var test2 = check(115);
var test3 = check(200);
var test4 = check(240);
Console.WriteLine("test1 {0} ,test2 {1} ,test3 {2} ,test4 {3} ",test1,test2,test3,test4);
string check(int value) => data.FirstOrDefault(pair => pair.Value.Contains(value)).Key;
}
You need to split the ranges, parse the numbers and check them:
var search = new {from = 110, to= 115};
var found = "100:105,110:120,150:200,240:245"
.Split(',') //split in parts like 100:105
.Select(p => {
var parts = p.Split(':'); // split the range from/to
var from = int.Parse(parts[0]); //convert from/to to ints
var to = int.Parse(parts[1]);
return new { from, to };
})
//check if any range matches the search values
.Any(range => search.from >= range.from && search.to <= range.to);
Console.WriteLine($"Found: {found}");
bool IsInRange(int ibegin, int iend, string BeginEnd)
{
string[] strBeginEnd = BeginEnd.Split(',');
foreach (var range in strBeginEnd)
{
var rangeArray = range.Split(':');
if (ibegin >= int.Parse(rangeArray[0]) && iend <= int.Parse(rangeArray[1]))
{
return true;
}
}
return false;
}
Related
I am trying to merge equal opening hours on consecutive days.
public class AgendaDay {
public string Day;
public string AM;
public string PM;
public AgendaDay(string day, string aM, string pM)
{
Day = day;
AM = aM;
PM = pM;
}
}
var agenda = new List<AgendaDay>() {
new AgendaDay("Mon", "0900-1200", "1400-1700"),
new AgendaDay("Tue", "0900-1200", "1400-1700"),
new AgendaDay("Wed", "", "1400-1700"),
new AgendaDay("Thu", "0900-1200", "1400-1700"),
new AgendaDay("Fri", "0900-1200", "1400-1700"),
new AgendaDay("Sat", "0900-1200", ""),
null
};
Reducing it to :
var expected = #"Mon-Tue: 09H00-12H00 / 14H00-17H00
Wed: 14H00-17H00
Thu-Fri: 09H00-12H00 / 14H00-17H00
Sat: 09H00-12H00";
For now I have:
public class ShortAgendaDay
{
public List<string> Days;
public string AM;
public string PM;
public ShortAgendaDay(List<string> days, string aM, string pM)
{
Days = days;
AM = aM;
PM = pM;
}
}
private static string ShrinkOpenningHour( List<AgendaDay> agenda)
{
var temp = agenda.Where(x=> x!=null).ToArray();
List<ShortAgendaDay> sum = new List<ShortAgendaDay>();
for (var i = 0; i < temp.Count(); i++)
{
if (i == 0) continue;
var last = temp[i - 1];
var curr = temp[i];
if (last.AM == curr.AM && last.PM == curr.PM) {
}
}
throw new NotImplementedException();
}
My idea was to reduce it to a list like:
{
day:["Mon","Tue"],
hour: "09H00-12H00 / 14H00-17H00"
},
{
day:["Wed"],
hour:"14H00-17H00"
},
{
day:["Thu","Fri"],
hour:"09H00-12H00 / 14H00-17H00"
}
Then to take only the First and the Last from the list of Day.
The format from "0900-1200" to "09h00-12h00" is not an issue you can ignore it in your answer.
"0900-1400", "1400-1700" is only equals to "0900-1400", "1400-1700". there is no trick like "0900-1000", "1000-1700". Overlapping timestamp do not really matter. It's a string and must be handled as a string, not timestamps with overlapping timespans.
Here is the merging:
private string ShrinkOpenningHour(List<AgendaDay> agenda)
{
var temp = agenda.Where(x => x != null).ToArray();
List<ShortAgendaDay> sum = new List<ShortAgendaDay>();
for (var i = 0; i < temp.Count(); i++)
{
if (i == 0 || (temp[i - 1].heureAM == temp[i].heureAM && temp[i - 1].heurePM == temp[i].heurePM))
{
var existingEntry = sum.Where(x => x.AM == temp[i].heureAM && x.PM == temp[i].heurePM);
if (existingEntry.Count() == 1)
{
existingEntry.First().Days.Add(temp[i].jour);
}
else
{
sum.Add(new ShortAgendaDay(new List<string>() { temp[i].jour }, temp[i].heureAM, temp[i].heurePM));
}
}
}
return string.Join(Environment.NewLine, sum.Select(x => FormatHorraire(x)));
}
And as bonus the formating:
private string FormatHorraire(ShortAgendaDay x)
{
string days = string.Join(" - ", new String[] { x.Days.First(), x.Days.Last() }.Where(ar => ar != null).Distinct());
string hour = FormatHorraire(x.AM, x.PM);
return days + " : " + hour;
}
private string FormatHorraire(string am, string pm)
{
return string.Join(" / ", new string[] { am, pm }.Where(y => !string.IsNullOrWhiteSpace(y) && y.Length > 7).Select(y => y.Insert(2, "H").Insert(8, "H")));
}
I want to search the penultimate row in the first.csv which date is 1975-01-03 and the Lemon value is 17.0, after I search in the second.csv the same date which lemon is 19.0
After catching both values, I compute the difference 17.0 - 19.0 = -2.0
The next step is to sum the difference -2 to all Lemon's values in second.csv from the date 1975-01-03 to the end 1975-01-09
The final step is to write the third.csv where we add the first.csv until the date 1975-01-02 and the sum we've done with second.csv from 1975-01-03 to the end 1975-01-09
first.csv
Date,Lemon
1974-12-31,19.0
1975-01-02,18.0
1975-01-03,17.0
1975-01-06,16.0
second.csv
Date,Lemon
1975-01-02,18.0
1975-01-03,19.0
1975-01-06,19.5
1975-01-07,19.5
1975-01-08,18.0
1975-01-09,17.0
third.csv
Date,Lemon
1974-12-31,19.0
1975-01-02,18.0
1975-01-03,17.0
1975-01-06,17.5
1975-01-07,17.5
1975-01-08,16.0
1975-01-09,15.0
All in all, the read from CSV is not as important as to obtain the third result in an Array, DataTable, Dictionary or whatever. Thanks
Start with a handy struct to make the coding easier:
public struct Line
{
public DateTime Timestamp;
public decimal Lemon;
}
Then you can write a simple function to load your CSV files:
Func<string, Line[]> readCsv =
fn =>
File
.ReadLines(fn)
.Skip(1)
.Select(x => x.Split(','))
.Select(y => new Line()
{
Timestamp = DateTime.Parse(y[0]),
Lemon = decimal.Parse(y[1])
})
.ToArray();
Now the rest is just a reading the files and a couple of LINQ queries before writing out the results:
Line[] first = readCsv(#"C:\_temp\first.csv");
Line[] second = readCsv(#"C:\_temp\second.csv");
Line difference =
(
from pen in first.Skip(first.Length - 2).Take(1)
from mtch in second
where mtch.Timestamp == pen.Timestamp
select new Line()
{
Timestamp = pen.Timestamp,
Lemon = pen.Lemon - mtch.Lemon
}
).First();
IEnumerable<string> result =
new [] { "Date,Lemon" }
.Concat(
first
.Where(x => x.Timestamp < difference.Timestamp)
.Concat(
second
.Where(x => x.Timestamp >= difference.Timestamp)
.Select(x => new Line()
{
Timestamp = x.Timestamp,
Lemon = x.Lemon + difference.Lemon
}))
.Select(x => String.Format(
"{0},{1}",
x.Timestamp.ToString("yyyy-MM-dd"),
x.Lemon)));
File.WriteAllLines(#"C:\_temp\third.csv", result);
The result I get is:
Date,Lemon
1974-12-31,19.0
1975-01-02,18.0
1975-01-03,17.0
1975-01-06,17.5
1975-01-07,17.5
1975-01-08,16.0
1975-01-09,15.0
This looks like homework, I strongly advice you to do this exercice by yourself by learning about LINQ (just google it). If you are stuck or can't find the solution here is a way to do it :
class LemonAtDate
{
public DateTime Date { get; set; }
public double Value { get; set; }
public LemonAtDate(DateTime Date, double Value)
{
this.Date = Date;
this.Value = Value;
}
public static List<LemonAtDate> LoadFromFile(string filepath)
{
IEnumerable<String[]> lines = System.IO.File.ReadLines(filepath).Select(a => a.Split(','));
List<LemonAtDate> result = new List<LemonAtDate>();
int index = 0;
foreach (String[] line in lines)
{
index++;
if (index == 1) continue; //skip header
DateTime date = DateTime.ParseExact(line[0], "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture);
double value = Double.Parse(line[1], System.Globalization.CultureInfo.InvariantCulture);
result.Add(new LemonAtDate(date, value));
}
return result;
}
public static void WriteToFile(IEnumerable<LemonAtDate> lemons, string filename)
{
//Write to file
using (var sw = new System.IO.StreamWriter(filename))
{
foreach (LemonAtDate lemon in lemons)
{
sw.WriteLine("Date,Lemon");//Header
string date = lemon.Date.ToString("yyyy-MM-dd");
string value = lemon.Value.ToString();
string line = string.Format("{0},{1}", date, value);
sw.WriteLine(line);
}
}
}
}
static void Main(string[] args)
{
//Load first file
List<LemonAtDate> firstCsv = LemonAtDate.LoadFromFile("first.csv");
//Load second file
List<LemonAtDate> secondCsv = LemonAtDate.LoadFromFile("second.csv");
//We need at least two rows
if (firstCsv.Count >= 2)
{
//Penultimate row in first file
LemonAtDate lemonSecondLast = firstCsv[firstCsv.Count - 2];
//Find the value 19 in the second file
LemonAtDate lemonValue19 = secondCsv.Where(x => x.Value == 19).FirstOrDefault();
//Value found
if (lemonValue19 != null)
{
double delta = lemonSecondLast.Value - lemonValue19.Value;
//Get the items between the dates and add the delta
DateTime dateStart = new DateTime(1975, 1, 3);
DateTime dateEnd = new DateTime(1975, 1, 9);
IEnumerable<LemonAtDate> secondFileSelection = secondCsv.Where(x => x.Date >= dateStart && x.Date <= dateEnd)
.Select(x => { x.Value += delta; return x; });
//Create third CSV
List<LemonAtDate> thirdCsv = new List<LemonAtDate>();
//Add the rows from the first file until 1975-01-02
DateTime threshold = new DateTime(1975, 1, 2);
thirdCsv.AddRange(firstCsv.Where(x => x.Date <= threshold));
//Add the rows from the second file
thirdCsv.AddRange(secondFileSelection);
//Write to file
LemonAtDate.WriteToFile(thirdCsv, "third.csv");
}
}
}
There are better ways of doing this, I took a quick and dirty procedural approach instead of an OO one. I also took a peek at the other answer and I see he parsed out the datetimes. I decided not to since you weren't doing any math specifically based on that. However his answer would be more flexible as with datetimes you can do more operations in the future.
List<string> csvfile1Text = System.IO.File.ReadAllLines("file1.csv").ToList();
List<string> csvfile2Text = System.IO.File.ReadAllLines("file2.csv").ToList();
Dictionary<string, double> csv1Formatted = new Dictionary<string, double>();
Dictionary<string, double> csv2Formatted = new Dictionary<string, double>();
Dictionary<string, double> csv3Formatted = new Dictionary<string, double>();
foreach (string line in csvfile1Text)
{
var temp= line.Split(',');
csv1Formatted.Add(temp[0], Double.Parse(temp[1]));
}
foreach (string line in csvfile2Text)
{
var temp = line.Split(',');
csv2Formatted.Add(temp[0], Double.Parse(temp[1]));
}
//operation 1
var penultimate = csv1Formatted["1974-01-03"];
var corrsponding = csv2Formatted["1974-01-03"];
var difference = penultimate - corrsponding;
//operation 2
var start = csv2Formatted["1974-01-03"];
var end = csv2Formatted["1974-01-09"];
var intermediate = csv2Formatted.Keys.SkipWhile((element => element != "1974-01-03")).ToList();
Dictionary<string, double> newCSV2 = new Dictionary<string, double>();
foreach (string element in intermediate)
{
var found = csv2Formatted[element];
found = found + difference;
newCSV2.Add(element, found);
}
//operation 3
intermediate = csv1Formatted.Keys.TakeWhile((element => element != "1975-01-03")).ToList();
foreach (string element in intermediate)
{
var found = csv1Formatted[element];
csv3Formatted.Add(element, found);
}
foreach (KeyValuePair<string,double> kvp in newCSV2)
{
csv3Formatted.Add(kvp.Key,kvp.Value);
}
//writing CSV3
StringBuilder sb = new StringBuilder();
foreach (KeyValuePair<string,double> kvp in csv3Formatted)
{
sb.AppendLine(kvp.Key + "," + kvp.Value);
}
System.IO.File.WriteAllText("C:\\csv3.csv", sb.ToString());
This is my favorite to use with CSV
https://github.com/kentcb/KBCsv
and if you want to work with csv entries as model for each row:
http://www.filehelpers.net/quickstart/
I hope you find this helpful.
Good luck :) Enjoy coding
I am using NEST (ver 0.12) Elasticsearch (ver 1.0) and I'm facing a problem with the facets.
Basically I'm expecting the results to be something similar to this
Between 18 and 25 (10)
Between 26 and 35 (80)
Greater then 35 (10)
But what I'm actually getting is this
between (99)
and (99)
35 (99)
26 (99)
This is my code
namespace ElasticSerachTest
{
class Program
{
static void Main(string[] args)
{
var setting = new ConnectionSettings(new Uri("http://localhost:9200/"));
setting.SetDefaultIndex("customertest");
var client = new ElasticClient(setting);
var createIndexResult = client.CreateIndex("customertest", new IndexSettings
{
});
// put documents to the index using bulk
var customers = new List<BulkParameters<Customer>>();
for (int i = 1; i < 100; i++)
{
customers.Add(new BulkParameters<Customer>(new Customer
{
Id = i,
AgeBand = GetAgeBand(),
Name = string.Format("Customer {0}", i)
}));
}
var bp = new SimpleBulkParameters()
{
Replication = Replication.Async,
Refresh = true
};
//first delete
client.DeleteMany(customers, bp);
//now bulk insert
client.IndexMany(customers, bp);
// query with facet on nested field property genres.genreTitle
var queryResults = client.Search<Customer>(x => x
.From(0)
.Size(10)
.MatchAll()
.FacetTerm(t => t
.OnField(f => f.AgeBand)
.Size(30))
);
var yearFacetItems = queryResults.FacetItems<FacetItem>(p => p.AgeBand);
foreach (var item in yearFacetItems)
{
var termItem = item as TermItem;
Console.WriteLine(string.Format("{0} ({1})", termItem.Term, termItem.Count));
}
Console.ReadLine();
}
public static string GetAgeBand()
{
Random rnd = new Random();
var age = rnd.Next(18, 50);
if (Between(age, 18, 25))
{
return "Between 18 and 25";
}
else if (Between(age, 26, 35))
{
return "Between 26 and 35";
}
return "Greater then 35";
}
public static bool Between(int num, int lower, int upper)
{
return lower <= num && num <= upper;
}
[ElasticType(Name = "Customer", IdProperty = "id")]
public class Customer
{
public int Id
{
get;
set;
}
public string Name
{
get;
set;
}
[ElasticProperty(Index = FieldIndexOption.not_analyzed)]
public string AgeBand
{
get;
set;
}
}
}
}
Thanks
Based on the output you are seeing, I do not think your FieldIndexOption.not_analyzed is being applied to the AgeBand field. As those facet results look like like analyzed values. You need to apply the mapping during the index creating process as part of your index settings. Please try the following index creation code:
var createIndexResult = client.CreateIndex("customertest", s => s
.AddMapping<Customer>(m => m
.MapFromAttributes()
)
);
Please see the Nest Documentation on Mapping for some other ways to add the mapping to your index as well.
Ok let me explain clearly what i want to achieve
It will be an object which will contain the below data - like an sql server table
BigInt parameter1
BigInt parameter2
string parameter3
these parameter1 and parameter2 both will compose the index (like primary key in sql-server table)
So this object will have like 500000 records like the above
And i will make fast look ups from this object like
return parameter3 where parameter1 <= value and value <= parameter2
What can be used for this ?
So far i tried these and they are slow
DataView.RowFilter = super slow
static Dictionary<Int64, KeyValuePair<Int64, string>> = slower than database query
Database query = where parameter1 & parameter2 composes primary key = slow since i need to make over 500000 query.
I also searched many questions at stackoverflow and none of them targeting between operator at integer keys. They are all multiple string key.
C# 4.0
Quick and dirty sketch:
public class GeoIp
{
private class GeoIpRecord
{
public long StartIp;
public long EndIp;
public string Iso;
}
private class GeoIpRecordComparer: IComparer<GeoIpRecord>
{
public int Compare(GeoIpRecord x, GeoIpRecord y)
{
return x.StartIp.CompareTo(y.StartIp);
}
}
private List<GeoIpRecord> geoIp;
private IComparer<GeoIpRecord> comparer;
public GeoIp()
{
this.geoIp = new List<GeoIpRecord>(500000)
{
new GeoIpRecord { StartIp = 1, EndIp = 2, Iso = "One" },
new GeoIpRecord { StartIp = 3, EndIp = 5, Iso = "Three" },
new GeoIpRecord { StartIp = 6, EndIp = 6, Iso = "Six" },
new GeoIpRecord { StartIp = 7, EndIp = 10, Iso = "Seven" },
new GeoIpRecord { StartIp = 15, EndIp = 16, Iso = "Fifteen" },
};
this.comparer = new GeoIpRecordComparer();
}
public string GetIso(long ipValue)
{
int index = this.geoIp.BinarySearch(new GeoIpRecord() { StartIp = ipValue }, this.comparer);
if (index < 0)
{
index = ~index - 1;
if (index < 0)
{
return string.Empty;
}
}
GeoIpRecord record = this.geoIp[index];
if (record.EndIp >= ipValue)
{
return record.Iso;
}
else
{
return string.Empty;
}
}
}
And the code that confirms the solution:
GeoIp geoIp = new GeoIp();
var iso1 = geoIp.GetIso(1); // One
var iso2 = geoIp.GetIso(2); // One
var iso3 = geoIp.GetIso(3); // Three
var iso4 = geoIp.GetIso(4); // Three
var iso5 = geoIp.GetIso(5); // Three
var iso6 = geoIp.GetIso(6); // Six
var iso7 = geoIp.GetIso(7); // Seven
var iso11 = geoIp.GetIso(11); //
var iso15 = geoIp.GetIso(15); // Fifteen
var iso17 = geoIp.GetIso(17); //
The List has to be filled with an ordered data.
List.BinarySearch Method (T, IComparer)
I don't think [that] ranges overlap.
This simplifies the problem a great deal: rather than performing a two-dimensional search, you can sort your list, and perform a one-dimensional binary search, like this:
var data = new List<Tuple<long,long,string>>(TotalCount);
var cmp = new TupleComparer();
data.Sort(cmp);
long item = ... // The item to be searched
var pos = data.BinarySearch(Tuple.Create(item, long.MinValue, String.Empty), cmp);
// It appears that your data has only non-empty strings, so it is guaranteed that
// pos is going to be negative, because Item3, the last tie-breaker, will be smaller
// than anything that you may have in the table
pos = ~pos;
if (pos != data.Count && data[pos].Item1 <= item && data[pos].Item2 >= item) {
Console.WriteLine("Found: '{0}'", data[pos].Item3);
} else {
Console.WriteLine("Not found");
}
Here is the TupleComparer class:
class TupleComparer : IComparer<Tuple<long,long,string>> {
public int Compare(Tuple<long,long,string> x, Tuple<long,long,string> y) {
var res = x.Item1.CompareTo(y.Item1);
if (res != 0) return res;
res = x.Item2.CompareTo(y.Item2);
return (res != 0) ? res : String.CompareOrdinal(x.Item3, y.Item3);
}
}
First of all sorry for my mistakes in English its not my primary language
i have a problem , i have a array like following
string[] arr1 = new string[] {
"Pakistan:4,India:3,USA:2,Iran:1,UK:0",
"Pakistan:4,India:3,USA:2,Iran:1,UK:0",
"India:4,USA:3,Iran:2,UK:1,Pakistan:0"
};
now i just want to know that how many times Pakistan comes with 1 ,
how many times with 2 , 3 , 4
and i need to know this about all India , USA , Iran , UK
Thanks in advance , you guys are my last hope .
This linq will convert the array into a Dictionary>, where the outer dictionary contains the countries names, and inner dictionaries will contain the ocurrence number (the number after ':') and the count for each ocurrence.
string[] arr1 = new string[]
{
"Pakistan:4,India:3,USA:2,Iran:1,UK:0",
"Pakistan:4,India:3,USA:2,Iran:1,UK:0",
"India:4,USA:3,Iran:2,UK:1,Pakistan:0"
};
var count = arr1
.SelectMany(s => s.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
.GroupBy(s => s.Split(':')[0], s => s.Split(':')[1])
.ToDictionary(g => g.Key,
g =>
{
var items = g.Distinct();
var result = new Dictionary<String, int>();
foreach (var item in items)
result[item] = g.Count(gitem => gitem == item);
return result;
});
// print the result
foreach(var country in count.Keys)
{
foreach(var ocurrence in count[country].Keys)
{
Console.WriteLine("{0} : {1} = {2}", country, ocurrence, count[country][ocurrence]);
}
}
I would use the String.Split(char[]) method and the String.SubString(int, int) method to inspect every 'country' inside your array and to get the number postfix of each country.
Try the following:
(The following code is now compiled and tested.)
Use a simple data structure to facilitate the task of holding the result of your operation.
public struct Result {
string Country { get; set; }
int Number { get; set; }
int Occurrences { get; set; }
}
// define what countries you are dealing with
string[] countries = new string[] { "Pakistan", "India", "USA", "Iran", "UK", }
Method to provide the overall result:
public static Result[] IterateOverAllCountries () {
// range of numbers forming the postfix of your country strings
int numbersToLookFor = 4;
// provide an array that stores all the local results
// numbersToLookFor + 1 to respect that numbers are starting with 0
Result[] result = new Result[countries.Length * (numbersToLookFor + 1)];
string currentCountry;
int c = 0;
// iterate over all countries
for (int i = 0; i < countries.Length; i++) {
currentCountry = countries[i];
int j = 0;
// do that for every number beginning with 0
// (according to your question)
int localResult;
while (j <= numbersToLookFor) {
localResult = FindCountryPosition(currentCountry, j);
// add another result to the array of all results
result[c] = new Result() { Country = currentCountry, Number = j, Occurrences = localResult };
j++;
c++;
}
}
return result;
}
Method to provide a local result:
// iterate over the whole array and search the
// occurrences of one particular country with one postfix number
public static int FindCountryPosition (string country, int number) {
int result = 0;
string[] subArray;
for (int i = 0; i < arr1.Length; i++) {
subArray = arr1[i].Split(',');
string current;
for (int j = 0; j < subArray.Length; j++) {
current = subArray[j];
if (
current.Equals(country + ":" + number) &&
current.Substring(current.Length - 1, 1).Equals(number + "")
)
result++;
}
}
return result;
}
The following should enable you to run the algorithm
// define what countries you are dealing with
static string[] countries = new string[] { "Pakistan", "India", "USA", "Iran", "UK", };
static string[] arr1 = new string[] {
"Pakistan:4,India:3,USA:2,Iran:1,UK:0",
"Pakistan:4,India:3,USA:2,Iran:1,UK:0",
"India:4,USA:3,Iran:2,UK:1,Pakistan:0"
};
static void Main (string[] args) {
Result[] r = IterateOverAllCountries();
}
The data structure you are using is not rich enough to provide you with that information. Hence you need to parse your string and create a new data structure to be able to provide (sring[][]):
string[] arr1 = new string[] {
"Pakistan,India,USA,Iran,UK",
"Pakistan,India,USA,Iran,UK",
"India,USA,Iran,UK,Pakistan"
};
string[][] richerArray = arr1.Select(x=> x.Split('\'')).ToArray();
var countPakistanIsFirst = richerArray.Select(x=>x[0] == "Pakistan").Count();
UPDATE
You seem to have changed your question. The answer applies to the original question.