How to clear a list in Dart? - dart

There are two options over there to clear some list
List<String> foo = ['a', 'b'];
...
foo = [];
// vs
foo.clear();
What is the best option? And when to use these variants?

.clear() will remove data from list with the same reference and foo = [] will have clear data with new reference
Note: .clear() is the best option

var list_name = new List()
--- creates a list of size zero
list_name = [val1,val2,val3]
--- a list containing the specified values
list_name = []
--- clear elements with new reference
list_name.clear()
--- removes every element from the list, but retains the list itself and it's type cast.
--- it's best option to remove all elements of list.

Related

How to add a prefix to every element of a set in Dart?

I initialize a set as
Set<String> ids = <String>{'1','2','3','4','5'};
How can I add a prefix such as ios_ to the set of ids such that the result is
Set<String> ids = <String>{'ios_1','ios_2','ios_3','ios_4','ios_5'};
You can use map() :
var result = ids.map((val) => 'ios_$val').toSet();

How to find an object by a property from a List of List of objects in dart?

Hello I am new to dart and trying to find an item by property name in a list of list.
class Product{
String id;
String title;
Product(this.id,this.title);
}
void main(){
List<List<Product>> allProdcuts=[
//New Prodcuts
[
Product("1","Hammer"),
Product("3","Nails"),
Product("2","Screws"),
],
futureItems,
//Old Prodcuts
[
Product("4","Rock"),
Product("5","Paper"),
Product("6","Scissor"),
],
//Rare Items
[
Product("7","Plank"),
Product("8","Wires"),
Product("9","Box"),
],
];
print(allProdcuts.where((itemsList)=>itemsList.contains((product)=>product.title='Wires')));
//Returns ()
}
I have tried using for a single List:
List<Product> futureItems= [
Product("101","Galactic Hammer"),
Product("301","Galactic Nails"),
Product("201","Galactic Screws"),
];
print(newProduct.firstWhere((p)=>p.title=='Hammer'));
//Instance of 'Product'
Also tried this:
print(allProdcuts.map((itemList)=>itemList.firstWhere((p)=>p.title=='Nails')));
// Bad state: No elementError: Bad state: No element.
But there is an element with the title='Nails'.I don't understand what I am doing wrong.
You are calling itemList.firstWhere((p)=>p.title=='Nails') on each list, also the ones with no element with title "Nails". Since firstWhere throws if there is no matching value, it does that for two of your three lists. Also, in the example, itemsList.contains(...) does not take a callback, so you are just checking whether a function is in the list, which it isn't. You might want to use any for that, but it won't solve the problem here.
To do this efficiently, I'd probably create helper function:
Product findByTitle(List<List<Product>> allProducts, String title) {
for (var products in allProducts) {
for (var product in products) {
if (product.title == title) return product;
}
}
// Or return `null`.
throw ArgumentError.value(title, "title", "No element with that title");
}
The return in the middle allows you to skip out of the double iteration the moment you have a match, something which is harder to do with firstWhere/map/forEach etc.
One alternative solutions would be:
var product = allProducts.expand((l) => l.where((p) => p.title == title)).first;
which finds all the products with the given title and flattens them into a single iterable, then picks the first one (if there are any). Because iterables are lazy, it will actually stop at the first match.
There are many ways to solve this.
One example is to use the forEach() method:
allProdcuts.forEach(
(List<Product> l)=>l.forEach(
(Product p){
if (p.title=="Nails")
print(p.id);
}
)
);
The for each method receives a function and applies this function to every element on the list. If you have a lists of lists, you can do this twice to get a function applied to each element of the sub lists.
The above code prints 3, which is the desired result.
Another solution would be to flatten the list first, so you can have an easier search later.
print(allProdcuts.any((innerListOfProducts) =>
innerListOfProducts.any((product) => product.title == 'Wires')));
This code will return true if 'Wires' is in the inner list, and false otherwise.

Binding search on NavigationList

My search method is working only on the first node of my jsonmodel, do i need to make another filter ?
///View
<tnt:NavigationList id="navlist" items="{path:'cars>/Desc'}" >
<tnt:NavigationListItem id="navlistitem" text="{cars>TITLE}" expanded="true" items="{path:'cars>ITEMS',templateShareable:true}"
key="{cars>number}">
<tnt:NavigationListItem id="navListItemSecond" text="{cars>TITLE}" key="{cars>number}">
</tnt:NavigationListItem>
</tnt:NavigationListItem>
</tnt:NavigationList>
//Controller (The search method)
onLiveSearch:function(evt) {
var filterString = evt.getParameter('newValue');
var filters = [];
var tree = this.getView().byId('navlist');
var binding = tree.getBinding('items');
if ( filterString && filterString.length > 0 ) {
var filter1 = new sap.ui.model.Filter( 'TITLE', sap.ui.model.FilterOperator.Contains,
filterString );
filters.push( filter1 );
}
binding.filter(filters);
},
Your question is somewhat similar to Filtering on Nested Aggregation Binding. Basically you have a two-level collection and (I guess) you want to be able to filter both levels (the items of the nav list and the child items of those items) with only one search.
What you have to do is actually filter both the top-level aggregations (the items aggregation of the NavigationList) and all the lower level aggregations (each of the items aggregations of the NavigationList's NavigationListItems).
Keep in mind that filtering on the navlistitem's items aggregation will not work, because this control is actually a template for the aggregation binding (it is cloned at runtime to obtain the items which are displayed). You will have to iterate through all the clones (= the items of the NavigationList) and apply the filter for each of them in order to achieve what you want.

List return Last item only mvc 4

below is my Action Method.It return Last item of list only. but I want list of Items in AList.
public ActionResult Ataxi(){
List<sub_employee> AList = new List<sub_employee>();
var alist = IM.getAvailableList().ToList();
foreach(var item in alist)
{
AList = db.sub_employee.Where(s => s.SE_ID == item).ToList();
}
return View(AList);
}
how do I get All elements in Alist. Can Somebody help me to solve this problem. thank you
I think you want something like this:
public ActionResult Ataxi(){
var list1 = IM.getAvailableList().ToList();
var list2 = db.sub_employee
.Where(x => list1.Contains(x.Id))
.ToList();
return View(list2);
}
In your example you keep overwriting the value of the list. You also check Where for each item of your original list against db.sub_employee, which is hard to read and not very efficient. You really only need to use Where once to filter the value whose key is not already in the list. Note that using Contains inside Where is horribly inefficient, but its simple to write and doesn't require creating new LINQ operators.
Also, on a style note, I would avoid starting local variable names with capital letters (Alist), and especially avoid local variables that only differ by capitalization (Alist vs alist). Conversely, it is standard to name types and properties starting with capital letters (sub_employee).

Create a numerical table from the values of a non numerical table

Backpack = {Potion = 'backpack',Stack = 'bag',Loot = 'derp', Gold = 'random'}
Backpack[1] ~= 'backpack' -- nope
As you guys can see, I cannot call Backpack[1] since its not a numeral table, how would I generate a table after the construction of Backpack, consisting only of it's values? for example:
Table_to_be_Constructed = {Value of Potion,Value of Stack,Value of Loot,Value of Gold} -- this is what i need
It seems simple but I couldn't find a way to do it.
I need it this way because i will run a numeric loop on Table_to_be_Constructed[i]
To iterate over all the key-value pairs in a table, use the pairs function:
local Table_to_be_Constructed = {}
for key, value in pairs(Backpack) do
table.insert(Table_to_be_Constructed, value)
end
Note: the iteration order is not defined. So, you might want to sort Table_to_be_Constructed afterwards.
By convention, the variable name _ is used to indicate a variable who's value won't be used. So, since you want only the values in the tables, you might write the loop this way instead:
for _, value in pairs(Backpack) do
For the updated question
Backpack has no order (The order in the constructor statement is not preserved.) If you want to add an order to its values when constructing Table_to_be_Constructed, you can do it directly like this:
local Table_to_be_Constructed = {
Backpack.Potion,
Backpack.Stack,
Backpack.Loot,
Backpack.Gold
}
Or indirectly like this:
local items = { 'Potion', 'Stack', 'Loot', 'Gold' }
local Table_to_be_Constructed = {}
for i=1, #items do
Table_to_be_Constructed[i] = Backpack[items[i]]
end

Resources