I have a list of data as key value pair say for example:
[0,"test"],
[1,"test1"],
[2,"test2"],
[0,"test5"],
[1,"test1"]
I just want to add this set of data into key-value pair as two individual set as follows
keyvaluepair1 =>[0,"test"],
[1,"test1"],
[2,"test2"],
keyvaluepair2 => [0,"test5"],
[1,"test1"]
If the pattern is that your key reverts to 0, then loop through the list and add a new dictionary to a list every time it resets.
//Your collection of KV Pair sets
var listOfKvs = new List<Dictionary<int,string>()
//an accumulator for the current set
var currentKvs = new Dictionary<int,string>()
var first = true;
foreach (var kv in keyvalues)
{
//The condition for when your key resets
if (kv.Key == 0)
{
if (first)
{
//we don't store the first dicitonary because it should be empty
first = false;
}
else
{
listOfKvs.Add(currentKvs);
}
currentKvs = new Dictionary<int, string>()
}
currentKvs.add(kv);
}
//Store the last dictionary
listOfKvs.add(currentKvs);
Related
I have the following:
IEnumerable<Personel> personel= page.Retrieve<Personel>....
Then I have List which contains only personelIDs
List<int> personelIDs....
I need to retrived all 'personels' from the IEnumerable and assign it into a new List which matches the personelIDs from 'personelIDs ' list.
I can do it my iterating and having verify the IDs and if they're equal assign it into another List,
but is there a short here where I can retrieve it without iterating or having multiple lines of code?
Basically Is there a way on how to shortened this
List<int> pIds = ....// contains only specific personellID's
IEnumerable personelIEn = // contains Personel data like personel IDs, name..etc
List<Personel> personel = personelIEn.ToList();
List<Personel> personelByTag = new List<Personel>();
foreach (Personel b in personel ) {
if (pIds.Contains(b.DocumentID)) {
personelByTag .Add(b);
}
}
return personelByTag ;
basically I'm trying to find ways how to shortened the above code
You can use a predicate:
public List<Personel> search(String documentId, List<Personel> list)
{
Predicate<Personel> predicate = (Personel personel) => (personel.Id== documentId);
return list.FindAll(predicate);
}
Could that help?
Suppose I have two class:
class Key {
private Integer id;
private String key;
}
class Value {
private Integer id;
private Integer key_id;
private String value;
}
Now I fill the first list as follows:
List<Key> keys = new ArrayLisy<>();
keys.add(new Key(1, "Name"));
keys.add(new Key(2, "Surname"));
keys.add(new Key(3, "Address"));
And the second one:
List<Value> values = new ArrayLisy<>();
values.add(new Value(1, 1, "Mark"));
values.add(new Value(2, 3, "Fifth Avenue"));
values.add(new Value(3, 2, "Fischer"));
Can you please tell me how can I rewrite the follow code:
for (Key k : keys) {
for (Value v : values) {
if (k.getId().equals(v.getKey_Id())) {
map.put(k.getKey(), v.getValue());
break;
}
}
}
Using Lambdas?
Thank you!
‐------UPDATE-------
Yes sure it works, I forget "using Lambdas" on the first post (now I added). I would like to rewrite the two nested for cicle with Lamdas.
Here is how you would do it using streams.
stream the keylist
stream an index for indexing the value list
filter matching ids
package the key instance key and the value instance value into a SimpleEntry.
then add that to a map.
Map<String, String> results = keys.stream()
.flatMap(k -> IntStream.range(0, values.size())
.filter(i -> k.getId() == values.get(i).getKey_id())
.mapToObj(i -> new AbstractMap.SimpleEntry<>(
k.getKey(), values.get(i).getValue())))
.collect(Collectors.toMap(Entry::getKey, Entry::getValue));
results.entrySet().forEach(System.out::println);
prints
Address=Fifth Avenue
Surname=Fischer
Name=Mark
Imo, your way is much clearer and easier to understand. Streams/w lambdas or method references are not always the best approach.
A hybrid approach might also be considered.
allocate a map.
iterate over the keys.
stream the values trying to find a match on key_id's and return first one found.
The value was found (isPresent) add to map.
Map<String,String> map = new HashMap<>();
for (Key k : keys) {
Optional<Value> opt = values.stream()
.filter(v -> k.getId() == v.getKey_id())
.findFirst();
if (opt.isPresent()) {
map.put(k.getKey(), opt.get().getValue());
}
}
For each article the user browses, I want to save the ID information.
I am using getstorage my code sample is below.
I can not find a true way also, i am looking best way to save id's list.
final box = GetStorage();
List<String> myFavoriteList = [];
saveFav(String id) {
myFavoriteList.add(id);
box.write('favoriteArticles', myFavoriteList.cast<String>());
}
ifExistInFav(String id) async {
bool ifExists = false;
List<String> my = (box.read('favoriteArticles').cast<String>() ?? []);
ifExists = my.contains(id) ? true : false;
return ifExists;
}
First, you need to define your list and convert it to String.
** note that if you use a custom data type ensure you convert your model to String.
then you can use the following to store a List as a String object
final box = GetStorage('AppNameStorage');
/// write a storage key's value
saveListWithGetStorage(String storageKey, List<dynamic> storageValue) async => await box.write(/*key:*/ storageKey, /*value:*/ jsonEncode(storageValue));
/// read from storage
readWithGetStorage(String storageKey) => box.read(storageKey);
the saving procee implemention:
saveList(List<dynamic> listNeedToSave) {
/// getting all saved data
String oldSavedData = GetStorageServices().readWithGetStorage('saveList');
/// in case there is saved data
if(oldSavedData != null){
/// create a holder list for the old data
List<dynamic> oldSavedList = jsonDecode(oldSavedData);
/// append the new list to saved one
oldSavedList.addAll(listNeedToSave);
/// save the new collection
return GetStorageServices().saveListWithGetStorage('saveList', oldSavedList);
} else{
/// in case of there is no saved data -- add the new list to storage
return GetStorageServices().saveListWithGetStorage('saveList', listNeedToSave);
}
}
/// read from the storage
readList() => GetStorageServices().readWithGetStorage('saveList');
then the usage:
onTap: () async => debugPrint('\n\n\n read list items ${jsonDecode(await readList())}\n\n\n', wrapWidth: 800),
I want to convert List of Maps into List of Map in dart. I want it Like this
{'frequency[]':Monday,'frequency[]':Tuesday,'frequency[]':Friday,'frequency[]':Saturday,}
This is the List Data I am Getting:
{frequency[]: Monday}, {frequency[]: Tuesday}, {frequency[]: Friday}, {frequency[]: Saturday}
This What I am doing so Far..
List list = [];
for (var i = 0; i < frequency.length; i++) {
var result = {for (var v in frequency) 'frequency[]': frequency[i]};
list.add(result);
// list.add('frequency[]':)
}
//{'frequency[]':Monday,'frequency[]':Tuesday,'frequency[]':Friday,'frequency[]':Saturday,}
print('This is the List Passed to the Api ${list.map((e) => e)}');
}
I would suggest using
for (var i in frequency.entries.toList()) {
list.add({i.key: i.value});
}
This iterates through the MapEntries in the map and makes a new map for each entry.
I assign the onValue to two variables in initState.
_boc.selectList(locationId).then((onValue) {
list = onValue;
filterList = onValue;
setState(() {});
});
When it comes to this function, I clear the filterList, but the length of the list become 0.
Future<List<Obk>> getSuggestion(
String search) async {
if (search == "empty") return [];
if (search == "error") throw Error();
filterList.clear();
print(list.length); // this print 0
});
...
}
but if I remove this line filterList = onValue; , it will show the length of the list.
How to prevent the items in list from deleted?
Instead of assigned the same List Object to both list and filteredList. You can make a new list object using List.from(). So that your original List remains unchanged.
_boc.selectList(locationId).then((onValue) {
list = onValue;
filterList = List.from(onValue);
setState(() {});
});
Now if you try to run your code and print the list length then you'll not get 0 after calling filterList.clear().
Future<List<Obk>> getSuggestion(
String search) async {
if (search == "empty") return [];
if (search == "error") throw Error();
filterList.clear();
print(list.length); // this will print list length
});
...
}