score:3
Accepted answer
try this:
declare @YourTable table (RowID int primary key, NextID int, TextValue varchar(50))
INSERT INTO @YourTable VALUES (1 , 12 ,'The quick')
INSERT INTO @YourTable VALUES (3 , 40 ,'jumps over')
INSERT INTO @YourTable VALUES (5 , null,'lazy dog.')
INSERT INTO @YourTable VALUES (12, 3 ,'brown fox')
INSERT INTO @YourTable VALUES (40, 5 ,'the')
;with cteview as (
SELECT * FROM @YourTable WHERE RowID=1
UNION ALL
SELECT y.* FROM @YourTable y
INNER JOIN cteview c ON y.RowID=c.NextID
)
select * from cteview
OPTION (MAXRECURSION 9999) --go beyond default 100 levels of recursion to 9999 levels
OUTPUT:
RowID NextID TextValue
----------- ----------- --------------------------------------------------
1 12 The quick
12 3 brown fox
3 40 jumps over
40 5 the
5 NULL lazy dog.
(5 row(s) affected)
score:0
LINQ answer:
table.OrderBy(sentence => sentence.NextID);
Edit: I hope I answered it correctly this time:
class Sentence
{
public int Id;
public int? NextId;
public string Text;
public Sentence(int id, int? nextId, string text)
{
this.Id = id;
this.NextId = nextId;
this.Text = text;
}
}
var Sentences = new [] {
new Sentence(1, 12, "This quick"),
new Sentence(3, 40, "jumps over"),
new Sentence(5, null, "lazy dog."),
new Sentence(12, 3, "brown fox"),
new Sentence(40, 5, "the"),
};
Func<int?, string> GenerateSentence = null;
GenerateSentence = (id) => id.HasValue? Sentences
.Where(s => s.Id == id.Value)
.Select(s => s.Text + " " + GenerateSentence(s.NextId))
.Single() : string.Empty;
Console.WriteLine(GenerateSentence(1));
score:0
If you are using LINQ to SQL/Entities, then the generated Sentence
class should have all those properties you mentioned, as well as an entity reference to the next sentence (let's call it NextSentence) from the foreign key.
Then you can just do:
Sentence s = Sentences.First();
StringBuilder sb = new StringBuilder();
do { sb.Append(s.Text); s = s.NextSentence; } while (s != null);
and sb.ToString()
will have your answer.
Source: stackoverflow.com
Related Query
- Order a query based on a field pointing to the same table
- Distinct in Linq based on only one field of the table
- LINQ MVC ViewModel: Multiple joins to the same table with optional field
- How can i copy data table records of different field name based on mapping list evaluating condition on source data table?
- How to TOP, ORDER BY and DISTINCT in the same query with Linq-To-Sql?
- SQL query that looks within the same table
- combine 2 queries from the same table into one linq query
- Linq to entities query with nested query on the same table
- Order by one element and return multi properties in the same LINQ query
- Can I Use The Same Linq Code to Query for Different Conditions?
- LinQ query group the same table twice
- LINQ query for grouping a table based on the values from another table
- How to get a Linq query to order results based on the order of arguments in a method signature
- Linq query on the same table with difference between rows
- Change the order by field based on a condition
- Entity Framework query the same table for the sequence of steps in WHERE
- Entity Framework Query based on child object filter and at the same time on the main object
- Can I assign the result of a Linq query to the source variable of the same query?
- The order of elements vary in an IQueryable, every time I query with the same condition
- Using Linq IQueryable, set which field to filter on depending on another field in the same table
- Select item from one list based on item in another list in the same order
- Lost join when self-joining a table on the same field
- C# - code to order by a property using the property name as a string
- Could not find an implementation of the query pattern for source type 'System.Data.Entity.DbSet'
- Should the order of LINQ query clauses affect Entity Framework performance?
- Filter the "Includes" table on Entity Framework query
- Entity Framework appears to be needlessly joining the same table twice
- Entity Framework Order by descending by row field in query
- LINQ query needs either ascending or descending in the same query
- Is there any way to create a LINQ query as a variable without having the data source (yet)?
More Query from same tag
- get attribute value from xsd node using LINQ
- C# LINQ comparing list values
- use wrapper class to initialize mutiple models for single view and LINQ Query
- Trying to map a property of an object to a string with AutoMapper
- How to concatenate all child elements with same names values using LINQ to XML
- how to use substring with LINQ
- Find Sum of product of 2 columns in LINQ
- check a List of values in db and retrieve items that fall under a Date Time Month Property
- Why can the anonymous type be changed if it is supposed to be immutable?
- read from csv to object[] C#
- How to get a running total of a decimal in a query?
- List Tuple DateTime
- Update all properties in list using linq
- C# LINQ: how to handle wildcard search?
- Max of 2 columns with multiple group by lambda expression entity framework
- Selecting Multiple Nodes on the Same Level w/ LINQ
- Find max value in List<int[]> by specific field in the array
- Copy one List to another List and SubList with LINQ
- Issue getting different types value of self join table
- merging two lists with diff structures C#
- VB.NET Search for objects in list and parse values of found object to array
- I need to check whether the data entered in form exists in database or not and if it exists redirect it to another page
- Using Linq and C#, how would I categorize a list of list and getting empty categories?
- NHibernate.Linq - How well does it work?
- LINQ Custom Sort
- EF4.2 extra left outer join to same table
- What Linq to Entities statement tells me if a particular child entity exists?
- Is it possible to have auto filters in Linq to SQL?
- Linq to SQL: Why am I getting IDENTITY_INSERT errors?
- combining these two methods into single one