May 2, 2009

Creating a Read Only List using LINQ




Have you felt the need of creating a read only List<> ? LINQ makes it very simple with the AsReadOnly() method. Here's how

C#


List<int> integ = new List<int>(){100,200,300,400,500};


IList<int> noModif = integ.AsReadOnly();


foreach (var i in noModif)


{


    // print i


}


 


try


{


    noModif.Add(600);


}


catch(Exception ex)


{


    // Exception raised stating that this collection is read only


}




VB.NET


 


Dim integ As New List(Of Integer)(New Integer() {100, 200, 300, 400, 500})


Dim noModif As IList(Of Integer) = integ.AsReadOnly()


For Each i In noModif


' print i


Next i


 


Try


    noModif.Add(600)


Catch ex As Exception


' Exception raised stating that this collection is read only


End Try




'Like' us on our FaceBook page if you find this blog useful. Thanks!


Did you like this post?
kick it on DotNetKicks.com Save on Delicious
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

comments

1 Response to "Creating a Read Only List using LINQ"
  1. Anonymous said...
    March 24, 2012 12:59 PM

    This is not LINQ. Method AsReadOnly is defined on List<T>.

 

Copyright © 2009-2012 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions