Modifying an array in Swift 2 - swift2

shoppingList[4...6] = ["Bananas", "Oranges"]
Don't use subscript syntax to append a new item to an array.
But I realize append one or more new items to array with ranges successed. For example:
var shoppingList : Array<String> = ["Bread", "Milk", "Blackingbar", "Chian", "baba", "Oppo", "Xiaomi"]
shoppingList[4...6] = ["Bananas", "Oranges", "Huewei", "5", "6"]
for obj in shoppingList {
print(obj)
}
Why we have recommeded "don't use it" ????

The precise quote from the documentation is
You can’t use subscript syntax to append a new item to the end of an
array.
Your code example replaces three items at index 4 - 6 with five other items simultaneously which is something different. As far as the subscripted range is not out of bounds the operation succeeds.

Im not sure why you would want to make 5 items replace the last 3 but if you need to do it, you could do this:
var shoppingList : Array<String> = ["Bread", "Milk", "Blackingbar", "Chian", "baba", "Oppo", "Xiaomi"]
shoppingList = shoppingList[0..<4] + ["Bananas", "Oranges", "Huewei", "5", "6"]

Related

Ruby: Hash w/ Arrays, Returning Associated Key If Value Is In Array

New to Ruby and have run out of ideas. I have an array of books that I would like to 1) Shelve 2) Find which shelf it is on 3) Remove it from the associated shelf if found. For brevity I have an array of 6 books. Each shelf contains 5 books.
library_catalog = [ "Book1", "Book2", "Book3", "Book4", "Book5", "Book6" ]
shelves = Hash.new(0)
catalog_slice = library_catalog.each_slice(5).to_a
count = 1
catalog_slice.each do | x |
shelves.merge!(count=>x)
count+=1
end
From this I know have a Hash w/ arrays as such
{1=>["Book1", "Book2", "Book3", "Book4", "Book5"], 2=>["Book6"]}
This is where I'm having trouble traversing the hash to find a match inside the array and return the key(shelf). If I have title = "Book1" and I am trying to match and return 1, how would I go about this?
I think this should work.
shelves.select { |k,v| v.include?("Book1")}.keys.first
selected the hashes that have a value equal to the title you are looking for (in this case "Book1")
get the keys for these hashes as an array
get the first entry in the array.
to remove the Book from the shelf try this:
key = shelves.select { |k,v| v.include?("Book1")}.keys.first
shelves[key].reject! { |b| b == "Book1" }
get a reference to the array and then reject the entry you want to remove

looping through 2 lists to get the results

I have two lists:
myObject object1 = new myObject(id = 1, title = "object1"};
myObject object2 = new myObject(id = 2, title = "object2"};
myObject object3 = new myObject(id = 3, title = "object3"};
//List 1
List<myObject> myObjectList = new List<myObject>{object1, object2, object3};
//List 2
List<int> idList = new List<int>{2, 3,5};
Now I need to get output as follows:
If a id is present in both the lists, I need to print "A",
if a id is present in list1 only, then I need to print "B",
...and if the id is present in list2 only, I need to print "C"
Can I use linq to achieve this?
I would simply use the inbuilt functions of Except and Intersect
List1.Intersect(List2) = "A"
List1.Except(List2) = "B"
List2.Except(List1) = "C"
There are plenty of resources online about how you could go about doing this, as one example (I didn't look into it too much), check out this link - Linq - Except one list with items in another
Hope this does the trick...

how to insert an array of id's into linq-to-sql query line in .net mvc 3

i want to get an array of id's which is like ["15", "26", "37", "48", "90"] and i want to get my remaining items from my remaining table that doesnt includes these supplier id's..
here what i done so far:
string[] arrgroupdetails;
arrgroupdetails = dataContext.GroupDetails.Select(c => c.supplier_id).ToArray();
var items = from thingies in dataContext.remainings where thingies.supplier_id.ToString() != arrgroupdetails.Any().ToString() select thingies;
so how can i achive this?
By heart, so do check syntax but someething like this should work:
var items = from thingies in dataContext.remainings
where !arrgroupdetails.Contains(thingies.supplier_id.ToString())
select thingies;

Linq List contains specific values

I need to know if the List I am working with contains only some specific values.
var list = new List<string> { "First", "Second", "Third" };
If I want to know if the List contain at least one item with the value "First" I use the Any keyword:
var result = list.Any(l => l == "First");
But how I can write a Linq expression that will return true/false only if the List contains "First" and "Second" values?
I'm not entirely sure what you want, but if you want to ensure that "First" and "Second" are represented once, you can do:
var result = list.Where(l => l == "First" || l =="Second")
.Distinct()
.Count() == 2;
or:
var result = list.Contains("First") && list.Contains("Second");
If you've got a longer "whitelist", you could do:
var result = !whiteList.Except(list).Any();
On the other hand, if you want to ensure that all items in the list are from the white-list and that each item in the white-list is represented at least once, I would do:
var set = new HashSet(list);
set.SymmetricExceptWith(whiteList);
var result = !set.Any();
EDIT: Actually, Jon Skeet's SetEquals is a much better way of expressing the last bit.
Your question is unclear.
From the first sentence, I'd expect this to be what you're after:
var onlyValidValues = !list.Except(validValues).Any();
In other words: after you've stripped out the valid values, the list should be empty.
From the final sentence, I'd expect this:
var validSet = new HashSet<string>(requiredValues);
var allAndOnlyValidValues = validSet.SetEquals(candidateSequence);
Note that this will still be valid if your candidate sequence contains the same values multiple times.
If you could clarify exactly what your success criteria are, it would be easier to answer the question precisely.
You can use Intersect to find matches:
var list = new List<string> { "First", "Second", "Third" };
var comparelist = new List<string> { "First", "Second" };
var test = list.Intersect(comparelist).Distinct().Count() == comparelist.Count();

How do you count the words in an array of strings with LINQ?

Given an array like {"one two", "three four five"}, how'd you calculate the total number of words contained in it using LINQ?
You can do it with SelectMany:
var stringArray = new[] {"one two", "three four five"};
var numWords = stringArray.SelectMany(segment => segment.Split(' ')).Count();
SelectMany flattens the resulting sequences into one sequence, and then it projects a whitespace split for each item of the string array...
I think Sum is more readable:
var list = new string[] { "1", "2", "3 4 5" };
var count = list.Sum(words => words.Split().Length);
Or if you want to use the C# language extensions:
var words = (from line in new[] { "one two", "three four five" }
from word in line.Split(' ', StringSplitOptions.RemoveEmptyEntries)
select word).Count();
Not an answer to the question (that was to use LINQ to get the combined word count in the array), but to add related information, you can use strings.split and strings.join to do the same:
C#:
string[] StringArray = { "one two", "three four five" };
int NumWords = Strings.Split(Strings.Join(StringArray)).Length;
Vb.Net:
Dim StringArray() As String = {"one two", "three four five"}
Dim NumWords As Integer = Split(Join(StringArray)).Length

Resources