Sort Dictionary swift 3.0 - sorting

At some point of coding, I require to sort dictionary to get ordered data based on the Dictionary's Key.
I tried to get the result by:
let sortedDict = dict.sorted { $0.key < $1.key }
It results into:
let dict = ["a0":1, "a3":2 , "a10":2, "a20":3]
Though, desired result:
let dict = ["a0":1, "a10":2, "a20":3, "a3":2]
Any suggestions would be most appreciated.
Thanks In advance.

Try This:
for i in 0..<parameters!.count {
let key = "q\(i)"
if httpBody.contains(key){
let regex = try! NSRegularExpression(pattern: "\\b\(key)\\b", options: .caseInsensitive)
httpBody = regex.stringByReplacingMatches(in: httpBody, options: [], range: NSRange(0..<httpBody.utf16.count), withTemplate: "q")
}
}
Simple sort function will not work here.

Dictionary is an unordered collection of data, so you can't create an ordered dictionary.

Related

How to add static information to dynamic data in Google Sheets?

I'm importing data into Google Sheets and then adding static information to it. I'd like my static data to be kept in alignment with a dynamic - is this possible? Is a script still required? Does anyone have an example?
it depends on your data structure, but there is a way with VLOOKUP formula
https://exceljet.net/excel-functions/excel-vlookup-function
Did you already find your solution to the problem? It sounds like you sort be able to sort the data with filters and still keep your note columns aligned.
this script could perhaps help:
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Sheet1");
var range = sheet.getRange("A1:Z");
function onEdit(e) {
range.sort([{column: 2, ascending: false}]);
}
Sheet1 = name of the sheet
A1:Z = range to be sorted
column: 2 = column B
ascending: false = descending

swift2: get array of keys from dictionary sorted by values

I am trying to get an array o keys from a dictionary where the array is sorted by values. For example:
//dictionary contains [alpha:C],[beta:A],[gamma:B]
My array should return:
//[beta, gamma, alpha]
I tried:
let keys = Array(myDictionary.keys).sort({ (a,b) -> Bool in
a.compare(b) == .OrderedAscending
})
but this returns the order by keys:
//[alpha, beta, gamma]
Given your dictionary
let dict = ["alpha":"C","beta":"A","gamma":"B"]
You can sort the keys by value with this code
let keysSortedByValue = dict.sort { $0.1 < $1.1 }.map { $0.0 }
// ["beta", "gamma", "alpha"]
Update
This screenshot to answer to your comment below

How do I Sort/OrderBy IList<Int32>

I'm trying Sort on IList, I have tried different approach but none works
here is what my code looks like:
IList<IWebElement> listCountIdsUi = driver.FindElements(By.CssSelector("table#ct_ tr td:nth-of-type(1)"));
List<Int32> ui = new List<Int32>();
foreach (IWebElement option in listCountIdsUi)
{
if (!option.Text.ToString().StartsWith("Page"))
{
ui.Add(Convert.ToInt32(option.Text));
}
}
the only way I able to figured out is working with ArrayList
ArrayList al = new ArrayList(ui);
al.Sort();
is not possible using IList ?
OrderBy does NOT modify the underlying collection - it returns an IEnumerable that gives you the items in the order you ask for. So you have a few options:
Use List.Sort(), which does modify the underlying collection:
ui.Sort();
Store the sorted list in a new variable
var uiSorted = ui.OrderBy(s => s);
replace the existing reference
ui = ui.OrderBy(s => s).ToList();
Have you tried the List<T>.Sort method?
ui.Sort((a, b) => a.CompareTo(b));
var uiOrdered = ui.OrderBy(s => s).ToList() should be all you need to do.

C# get enumeration index

I have this enumeration:
public enum SymbolPair
{
AUDJPY = 0, AUDNZD, AUDUSD, CADJPY, CHFJPY, EURCHF, EURGBP, EURJPY, EURUSD, GBPJPY, GBPUSD, NZDUSD, USDCAD, USDCHF, USDJPY
}
And I have a collection of symbol strings
List<string> symbols = new List<string>(){ };
Symbols are loaded into the collection dynamically depending on which symbols are entered in the input parameters. They can be loaded in any order and any count.
So for example one set can load in "EUR/USD", "CHFJPY", "GBPUSD"
I need to find the indexes corresponding to the index of the enumeration type. For example in this case I need the indexes 8, 4, and 10.
Can someone please give an idea how to do this with linq or delegates or any other efficient way.
Thanks
EDIT: I need something along these lines but this doesn't work since linq does return a single value. How can I get that single index?
SymbolPair[] enumList = (SymbolPair[])Enum.GetValues(typeof(SymbolPair));
foreach (string symbol in symbols)
{
int instrumentIndex = from symbolPair in enumList
where symbolPair.ToString() == symbol
select (int)symbolPair;
}
Ok i got it. Thanks anyways.
SymbolPair[] symbolEnumList = (SymbolPair[])Enum.GetValues(typeof(SymbolPair));
int instrumentIndex = (int)symbolEnumList.Single(symbolPair => symbolPair.ToString() == instr.Symbol.ToString());

Truncating a collection using Linq query

I want to extract part of a collection to another collection.
I can easily do the same using a for loop, but my linq query is not working for the same.
I am a neophyte in Linq, so please help me correcting the query (if possible with explanation / beginners tutorial link)
Legacy way of doing :
Collection<string> testColl1 = new Collection<string> {"t1", "t2", "t3", "t4"};
Collection<string> testColl2 = new Collection<string>();
for (int i = 0; i < newLength; i++)
{
testColl2.Add(testColl1[i]);
}
Where testColl1 is the source & testColl2 is the desired truncated collection of count = newLength.
I have used the following linq queries, but none of them are working ...
var result = from t in testColl1 where t.Count() <= newLength select t;
var res = testColl1.Where(t => t.Count() <= newLength);
Use Enumerable.Take:
var testColl2 = testColl1.Take(newLength).ToList();
Note that there's a semantic difference between your for loop and the version using Take. The for loop will throw with IndexOutOfRangeException exception if there are less than newLength items in testColl1, whereas the Take version will silently ignore this fact and just return as many items up to newLength items.
The correct way is by using Take:
var result = testColl1.Take(newLength);
An equivalent way using Where is:
var result = testColl1.Where((i, item) => i < newLength);
These expressions will produce an IEnumerable, so you might also want to attach a .ToList() or .ToArray() at the end.
Both ways return one less item than your original implementation does because it is more natural (e.g. if newLength == 0 no items should be returned).
You could convert to for loop to something like this:
testColl1.Take(newLength)
Use Take:
var result = testColl1.Take(newLength);
This extension method returns the first N elements from the collection where N is the parameter you pass, in this case newLength.

Resources