2

I'm trying to create a cookie that stores a list of properties that a user views.

I have created a test, and it works in part. Currently, each time i visit a page, it pulls the property ID from the URL and either creates a new string containing that URL, if if a cookie already exists, it'll append that property ID to it.

@{
    var rPropertyId = UrlData[0].AsInt(); 

    if(rPropertyId > 0){
        if (Request.Cookies["viewed_properties"] != null){
            var value = Request.Cookies["viewed_properties"].Value.ToString(); 
            var value1 = value + "." + rPropertyId;
            var newcookievalue = String.Join(".", value1.Split(new Char[] {'.'}).Distinct());
            Response.Cookies["viewed_properties"].Value = newcookievalue;
            Response.Cookies["viewed_properties"].Expires = DateTime.Now.AddYears(1); 
        } else {
            Response.Cookies["viewed_properties"].Value = rPropertyId.ToString();
            Response.Cookies["viewed_properties"].Expires = DateTime.Now.AddYears(1);            
        }
    }  
}

@if (Request.Cookies["viewed_properties"] != null){
    var mylist = Request.Cookies["viewed_properties"].Value.Split(new Char[] {'.'});
    foreach (var i in mylist)
    {
        <p>@i</p>
    }
}

What this process doesn't take into consideration, is that if a user visits the same property more than once, i still want only 1 entry of that ID in the cookie. How would i check this, convert it to an array?

Gavin5511
  • 791
  • 5
  • 31

1 Answers1

2

Enumerable.Distinct will makes sure you have no duplicates.

Something like:

 var newCookieValue = 
        String.Join(".",          
           currentCookieValue.Split(new Char[] {'.'}).Distinct());

To add latest to the end - one option is to remove first and add later:

 ....
    currentCookieValue.Split(new Char[] {'.'})
       .Where(s => s != newStringValueToAdd)
       .Distinct()
       .ToList()
       .Add(newStringValueToAdd)

Side note: cookie values have relatively small length restriction (What is the maximum size of a web browser's cookie's key?), so be careful adding arbitrary number of items to single cookie.

Community
  • 1
  • 1
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
  • Ok, so adding the "distinct" function ensures that are no duplicated, which is great. But if it does find a duplicate, it doesn't add the distinct entry to the end of the list? – Gavin5511 Apr 20 '15 at 20:34
  • for example if i browse property 1, then property 2, then property 3, then property 1 again, i'd expect the "1" to be at the end of the list? is there an overload for this? – Gavin5511 Apr 20 '15 at 20:35
  • @Gavin5511 there is no overload, you'd have to remove/add it your self (added sample). – Alexei Levenkov Apr 20 '15 at 20:44
  • I'm getting: Operator '!=' cannot be applied to operands of type 'string' and 'int'. Is there a typo in the "where" clause? – Gavin5511 Apr 20 '15 at 21:06