0

We've got a table in SQL Server that has values that are to appear in a couple of textboxes, if those textboxes are initially empty. Then the user can either add more details to the pre-loaded text, or remove it, whatever. It's to get the user started. Here's the table's schema:

CREATE TABLE [dbo].[PreloadTextbox](
[PreLoadNumber] [smallint] NOT NULL,
[DisplayOrder] [smallint] NOT NULL,
[LineToDisplay] [varchar](100) NULL,
CONSTRAINT [PK_PreloadTextbox] PRIMARY KEY CLUSTERED 
(
[PreLoadNumber] ASC,
[DisplayOrder] ASC
  )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

This table was initially used for a VB6 app written many years ago. We're re-writing it in WPF using C#. The field PreLoadNumber is associated with the textbox it's associated with, and of course the DisplayOrder is what order the records should appear in. What we should do is combine all of the records in the table into 1 large record, change the LineToDisplay from a VARCHAR(100) to VARCHAR(MAX), but that will have to wait until another day, as this table is still being used by the old VB6 app.

So what I'm hoping to find out is this; is it possible to combine all LineToDisplay for say PreLoadNumber == 1 (in the order specified by DisplayOrder) using LINQ? And if so, how is that done?

4

2 回答 2

1

我想你正在寻找这样的东西:

var results = dbContext.PreloadTextbox
                       .Where(x=> x.PreLoadNumber == 1)
                       .OrderBy(x=> x.DisplayOrder)
                       .Select(x=> x.LineToDisplay)
                       .ToArray();

//string array is joined here using a ",", change it as necessary 
string output = string.Join(",", results);
于 2013-11-05T21:44:17.090 回答
1

解决它的另一种方法可能是添加一个 SQL Server 视图,如下所示:

SELECT  pt.PreLoadNumber AS [PreLoadNumber]
       ,( SELECT    SUB.LineToDisplay AS [text()]
          FROM      [PreLoadTextbox] SUB
          WHERE     SUB.PreLoadNumber = pt.PreLoadNumber
          ORDER BY  SUB.DisplayOrder
        FOR
          XML PATH('')
        ) AS [LinesToDisplay]
FROM    ( SELECT DISTINCT
                    PreLoadNumber
          FROM      [PreLoadTextbox]
        ) pt

由于视图的预编译,这可能会提高性能。该视图将为您提供一个带有 的两列视图PreLoadNumber,并且所有视图都LineToDisplay连接在DisplayOrder它们之间而没有分隔符的情况下。如果您需要分隔符,您可以使用:

SELECT  pt.PreLoadNumber AS [PreLoadNumber]
       ,STUFF((   SELECT    ',' + SUB.LineToDisplay AS [text()]
          FROM      [PreLoadTextbox] SUB
          WHERE     SUB.PreLoadNumber = pt.PreLoadNumber
          ORDER BY  SUB.DisplayOrder
        FOR
          XML PATH('')
        ), 1, 1, '' ) AS [LinesToDisplay]
FROM    ( SELECT DISTINCT
                    PreLoadNumber
          FROM      [PreLoadTextbox]
        ) pt
于 2013-11-05T22:18:40.407 回答