I have two lists. lst contains ViewState Data i.e All the records of the gridview & second lstRank contains the list of integer(i.e ID) for only those records which are marked as checked (i.e Gridview contains a columns for checkbox). Now i want to update the lst bool status depending upon integer ID of lstRank. How it can be achieved by lambda expression
List<Tuple<int, string, bool>> lst = (List<Tuple<int, string,bool>>)ViewState["gvData"];
List<int> lstRank = gvDetails.Rows.OfType<GridViewRow>().Where(s => ((CheckBox)s.FindControl("chkSelect")).Checked)
.Select(s => Convert.ToInt32(((Label)s.FindControl("lblRankCD")).Text)).ToList();
Your question isn't clear, but I'm guessing you want to change lst's contents so that the boolean values are true if the int exists in lstRank, or false if not?
Obviously, tuples are immutable, so if you want to change one of the values, you would have to generate new tuple instances. It's not clear what you mean when you say you specifically want to do this with a lambda expression, but I assume you probably mean that you don't want a solution that involves an explicit loop. So how about this:
lst = lst.Select(oldValues =>
Tuple.Create(oldValues.Item1,
oldValues.Item2,
lstRank.Contains(oldValues.Item3))).ToList();
If lstRank is large, you might want to optimize by first building a HashSet out of it, since you'll be doing a lot of Contains calls.
Related
If I want to change a value on a list, I will return a new list with the new value instead of changing the value on the old list.
Now I have four types. I need to update the value location in varEnd, instead of changing the value, I need to return a new type with the update value
type varEnd = {
v: ctype;
k: varkind;
l: location;
}
;;
type varStart = {
ct: ctype;
sy: sTable;
n: int;
stm: stmt list;
e: expr
}
and sEntry = Var of varEnd | Fun of varStart
and sTable = (string * sEntry) list
type environment = sTable list;;
(a function where environment is the only parameter i can use)
let allocateMem (env:environment) : environment =
I tried to use List.iter, but it changes the value directly, which type is also not mutable. I think List.fold will be a better option.
The biggest issue i have is there are four different types.
I think you're saying that you know how to change an element of a list by constructing a new list.
Now you want to do this to an environment, and an environment is a list of quite complicated things. But this doesn't make any difference, the way to change the list is the same. The only difference is that the replacement value will be a complicated thing.
I don't know what you mean when you say you have four types. I see a lot more than four types listed here. But on the other hand, an environment seems to contain things of basically two different types.
Maybe (but possibly not) you're saying you don't know a good way to change just one of the four fields of a record while leaving the others the same. This is something for which there's a good answer. Assume that x is something of type varEnd. Then you can say:
{ x with l = loc }
If, in fact, you don't know how to modify an element of a list by creating a new list, then that's the thing to figure out first. You can do it with a fold, but in fact you can also do it with List.map, which is a little simpler. You can't do it with List.iter.
Update
Assume we have a record type like this:
type r = { a: int; b: float; }
Here's a function that takes r list list and adds 1.0 to the b fields of those records whose a fields are 0.
let incr_ll rll =
let f r = if r.a = 0 then { r with b = r.b +. 1.0 } else r in
List.map (List.map f) rll
The type of this function is r list list -> r list list.
I'm messing around a bit with F# and I'm not quite sure if I'm doing this correctly. In C# this could be done with an IDictionary or something similar.
type School() =
member val Roster = Map.empty with get, set
member this.add(grade: int, studentName: string) =
match this.Roster.ContainsKey(grade) with
| true -> // Can I do something like this.Roster.[grade].Insert([studentName])?
| false -> this.Roster <- this.Roster.Add(grade, [studentName])
Is there a way to insert into the map if it contains a specified key or am I just using the wrong collection in this case?
The F# Map type is a mapping from keys to values just like ordinary .NET Dictionary, except that it is immutable.
If I understand your aim correctly, you're trying to keep a list of students for each grade. The type in that case is a map from integers to lists of names, i.e. Map<int, string list>.
The Add operation on the map actually either adds or replaces an element, so I think that's the operation you want in the false case. In the true case, you need to get the current list, append the new student and then replace the existing record. One way to do this is to write something like:
type School() =
member val Roster = Map.empty with get, set
member this.Add(grade: int, studentName: string) =
// Try to get the current list of students for a given 'grade'
let studentsOpt = this.Roster.TryFind(grade)
// If the result was 'None', then use empty list as the default
let students = defaultArg studentsOpt []
// Create a new list with the new student at the front
let newStudents = studentName::students
// Create & save map with new/replaced mapping for 'grade'
this.Roster <- this.Roster.Add(grade, newStudents)
This is not thread-safe (because calling Add concurrently might not update the map properly). However, you can access school.Roster at any time, iterate over it (or share references to it) safely, because it is an immutable structure. However, if you do not care about that, then using standard Dictionary would be perfectly fine too - depends on your actual use case.
how to compare two objects using viewstate.
what is the meaning of below line.
if (!((byte[])ViewState["ROW"]).SequenceEqual(obj.RowID))
{
return null
}
can anyone please help on this
ViewState["ROW"] : This part will retrieve data from the ViewState stored with key ROW
(byte[])ViewState["ROW"] : This part will cast your data stored in ViewState to byte array
SequenceEqual : is extension method from System.Linq, which checks whether two sequences are same or not
((byte[])ViewState["ROW"]).SequenceEqual(obj.RowID) : Compares sequence of ViewState["Row"] and obj.RowID
if (!((byte[])ViewState["ROW"]).SequenceEqual(obj.RowID)) : This will return null if sequences of ViewState["Row"] and obj.RowID are not same.
what is the meaning of below line.
Basically, SequenceEqual is a LINQ Enumerable extension function which desinged to determine if a source sequence (e.g. byte[]) is equals to another sequence.
Assuming you are comparing two byte arrays (sequenses) in your provided code, if they both equals in their sequence of elements, you will get true, otherwise, false would be the result.
For example, the following sequences are equals and the SequenceEqual will return true:
byte[] chars1 = {56,32,12,32,65, 87};
byte[] chars2 = {56,32,12,32,65, 87};
bool res = chars1.SequenceEqual(chars2); // Will return true
In this jsfiddle(http://jsfiddle.net/3NUJE/3/), I'm changing the data key bound to an object by passing a different string:
// Create rectangles
var rects = chart
.selectAll('rect')
.data(data, function(d) {return d + 'a'})
...
// Update data -- all should be removed
d3.selectAll('rect')
.data([5,6], function(d) { return(d + 'b'); })
.exit()
.transition()
.delay(2000)
.remove();
Unfortunately, these are bound to the same key (ie, 5 and 6 don't get removed)-- is it possible to differentiate them without changing the data array that I pass?
The key function that you can pass to .data() is executed for both the new data elements and the ones that are bound already. That is, when you bind data and use a key function, the key returned by that function isn't stored with the data. This means that it doesn't matter what you change the key function to for your second call, as long as the actual data is the only thing that changes the new data will match existing data.
For example for data element 5 the key function returns 5b. For the data already bound to the elements it returns 1b, 4b, 5b, etc. The two 5b match.
You could pass objects with more attributes instead of numbers and then use another attribute (which would have to be different for the new data) as a key.
I have the following structure of a dictionary in Erlang:
Key: {element_name, a, element_type, type_1}
Value: [list].
Dictionary: (({element_name, a, element_type, type_1},[List]), ({element_name, b, element_type, type_2},[List])).
I would like to update a certain key-value pair and insert some new data into the 'key' tuple (not into 'value' list):
1. Value_list = dict:fetch({element_name, a, element_type, _}, Dict).
2. Dict2 = dict:erase ({element_name, a, element_type, _}, Dict).
3. Dict3 = dict:store ({element_name, a, element_type, New_type}, Value_list, Dict2).
The problem is that at line 1 Erlang says that variable "_" is unbound.
It seems that I cannot fetch a value by providing only a part of the key if the key is a tuple. Is this true?
Is it actually possible to update a key in a dictionary?
Is there any shorter way to do this instead of doing 1,2 and 3?
dict doesn't support what you want to do. you will have to know the key, erase the old key/value pair, and store a new one.
take a look at ets. you can use ets:match to find keys that match your spec. you'll still have to delete the old key/value pair and insert a new one.
If you insist on updating the Key in the dictionary without deleting it and later storing a new value against it, i suggest that you first convert your Dict into a list by this: dict:to_list/1. Consider this piece of code:
Fun_to_match_key = fun({{element_name, a, element_type, _} = Key,Value})->
%% do some stuff here with the Key and value and assuming
%% this fun returns the new Key-Value pair you want
New_Key = update_my_key(Key),
New_Value = update_my_value_if_need_to(Value),
{New_Key,New_Value};
(Any)-> Any
end,
%% Then in one operation, you convert the dict into a list, apply the
%% fun above in a list comprehension and convert the list back to a dict
New_dict = dict:from_list([Fun_to_match_key(Key_Value_Pair) || Key_Value_Pair <- dict:to_list(Old_Dict)]),
New_dict.
Converting the dict into a list will give you a proplist() which is much easier to manipulate either Key or value. You could use any method say, recursion with several clauses in which you pattern match the nature of Key you want to manipulate, in the above example i have chosen to use a fun within a list comprehension.
That should do the trick!