LiveLinq > How to use LiveLinq > How to Create a Live View |
Consider a simple query like the following:
C# |
Copy Code
|
---|---|
from a in A where a.p == 1 select a |
In standard LINQ, the result of this query is a snapshot. The result collection is formed at the time when the query is executed and it does not change after that. If one of its objects changes so it no longer satisfies the condition, that object will not be removed from the result collection. And if an object in A changes so it now satisfies the condition, that object will not be added to the result collection. The result of even such a simple query is not live, not dynamic, does not change automatically when the base collection A changes, not kept in sync automatically with the base data.
In LiveLinq, if we create a view based on that query, it will be live, dynamic, will change automatically when the base data changes, will be automatically kept in sync with the base data.
All we need to do to make a view out of this query is to use the extension method .AsLive():
C# |
Copy Code
|
---|---|
var view = from a in A.AsLive() where a.p == 1 select a; |
The AsLive() extension method is the analog of AsIndexed()|keyword=AsIndexed Method/ToIndexed(), it can be used everywhere where the AsIndexed()|keyword=AsIndexed Method/ToIndexed() extension methods can be used. So, live views are supported in all cases in LiveLinq to Objects, LiveLinq to XML and LiveLinq to DataSet (with some restrictions on the supported query operators, see Query Operators Supported in Live Views). The difference between AsIndexed()|keyword=AsIndexed Method/ToIndexed() and AsLive() is that AsLive() creates a view, thus enabling LiveLinq both to query to populate the view and to maintain the view after it has been initially populated. The AsIndexed()|keyword=AsIndexed Method/ToIndexed() extension methods do only the first part, enable LiveLinq querying.
The example above is a very simple one, it's just one simple Where condition. There are other tools that can do the same, for example, DataView in ADO.NET or CollectionView in WPF. The power of LiveLinq is that it supports most of the LINQ operators, including joins and others. So you can create a live view based not just on a simple condition, but on virtually any query you need.