C#LINQ返回所有合并的结果

时间:2019-11-29 06:46:41

标签: c# linq

我想从两个表的联接返回结果集。到目前为止,我已经参加了会议,但是很难弄清最后一部分(或者可能需要重新布线)。

var x = _context.GameHasPlayers
    .Join(_context.Games, 
        ghp => ghp.GameId,
        g => g.Id,
        (gameHasPlayer, game) => /*What goes here*/ );

在SQL中,我只需编写以下代码:

select * from GameHasPlayer ghp
join Game g on g.Id = ghp.GameId

比方说,这应该返回2场比赛,每场比赛有2位玩家,因此总共有4行。

如果我在c#查询的最后一行中使用它,它将运行:

(gameHasPlayer, game) => new Game { });

但是我只是得到了四个(如预期的那样)新的空Game类,所以我在如何返回整个结果集(即两个表的所有4行都已连接)上苦苦挣扎-我需要创建一些首先结合了GameGameHasPlayer的新模型/视图?

(例如,在SQL中,我可以创建实现上述SQL查询的视图并返回通用数据集,还是重新创建视图c#端?)

-----编辑-----

我也在下面尝试:

var x = from ghp in _context.GameHasPlayers
    from g in _context.Games
    where g.Id == ghp.GameId
    select (g) // or select (ghp)

这给了我ACTUAL的结果,但仅适用于gghp-如果我尝试select (g, ghp),那只会打不起来!

2 个答案:

答案 0 :(得分:0)

您必须了解C#将需要一些关于您返回的实例的结构的想法。遗憾的是,简单地将两个本来不相关的类合并在一起是不可行的。

幸运的是,这就是select语句为您提供的:一种快速创建匿名对象以存储在结果集中的方法。
select (g)之所以有用,是因为编译器知道g的类型。但是,如果要加入gghp,则需要构造一个新类型:

select(r => new {
   Id = g.Id,
   GameId = ghd.GameId,
   // ...
})

答案 1 :(得分:0)

您可以使用以下两种语法之一:

 * Performs document text OCR with PDF/TIFF as source files on Google Cloud Storage.
 *
 * @param gcsSourcePath The path to the remote file on Google Cloud Storage to detect document
 *                      text on.
 * @param gcsDestinationPath The path to the remote file on Google Cloud Storage to store the
 *                           results on.
 * @throws Exception on errors while closing the client.
 */
public static void detectDocumentsGcs(String gcsSourcePath, String gcsDestinationPath) throws
    Exception {
  try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) {
    List<AsyncAnnotateFileRequest> requests = new ArrayList<>();

    // Set the GCS source path for the remote file.
    GcsSource gcsSource = GcsSource.newBuilder()
        .setUri(gcsSourcePath)
        .build();

    // Create the configuration with the specified MIME (Multipurpose Internet Mail Extensions)
    // types
    InputConfig inputConfig = InputConfig.newBuilder()
        .setMimeType("application/pdf") // Supported MimeTypes: "application/pdf", "image/tiff"
        .setGcsSource(gcsSource)
        .build();

    // Set the GCS destination path for where to save the results.
    GcsDestination gcsDestination = GcsDestination.newBuilder()
        .setUri(gcsDestinationPath)
        .build();

    // Create the configuration for the output with the batch size.
    // The batch size sets how many pages should be grouped into each json output file.
    OutputConfig outputConfig = OutputConfig.newBuilder()
        .setBatchSize(2)
        .setGcsDestination(gcsDestination)
        .build();

    // Select the Feature required by the vision API
    Feature feature = Feature.newBuilder().setType(Feature.Type.DOCUMENT_TEXT_DETECTION).build();

    // Build the OCR request
    AsyncAnnotateFileRequest request = AsyncAnnotateFileRequest.newBuilder()
        .addFeatures(feature)
        .setInputConfig(inputConfig)
        .setOutputConfig(outputConfig)
        .build();

    requests.add(request);

    // Perform the OCR request
    OperationFuture<AsyncBatchAnnotateFilesResponse, OperationMetadata> response =
        client.asyncBatchAnnotateFilesAsync(requests);

    System.out.println("Waiting for the operation to finish.");

    // Wait for the request to finish. (The result is not used, since the API saves the result to
    // the specified location on GCS.)
    List<AsyncAnnotateFileResponse> result = response.get(180, TimeUnit.SECONDS)
        .getResponsesList();

    // Once the request has completed and the output has been
    // written to GCS, we can list all the output files.
    Storage storage = StorageOptions.getDefaultInstance().getService();

    // Get the destination location from the gcsDestinationPath
    Pattern pattern = Pattern.compile("gs://([^/]+)/(.+)");
    Matcher matcher = pattern.matcher(gcsDestinationPath);

    if (matcher.find()) {
      String bucketName = matcher.group(1);
      String prefix = matcher.group(2);

      // Get the list of objects with the given prefix from the GCS bucket
      Bucket bucket = storage.get(bucketName);
      com.google.api.gax.paging.Page<Blob> pageList = bucket.list(BlobListOption.prefix(prefix));

      Blob firstOutputFile = null;

      // List objects with the given prefix.
      System.out.println("Output files:");
      for (Blob blob : pageList.iterateAll()) {
        System.out.println(blob.getName());

        // Process the first output file from GCS.
        // Since we specified batch size = 2, the first response contains
        // the first two pages of the input file.
        if (firstOutputFile == null) {
          firstOutputFile = blob;
        }
      }

      // Get the contents of the file and convert the JSON contents to an AnnotateFileResponse
      // object. If the Blob is small read all its content in one request
      // (Note: the file is a .json file)
      // Storage guide: https://cloud.google.com/storage/docs/downloading-objects
      String jsonContents = new String(firstOutputFile.getContent());
      Builder builder = AnnotateFileResponse.newBuilder();
      JsonFormat.parser().merge(jsonContents, builder);

      // Build the AnnotateFileResponse object
      AnnotateFileResponse annotateFileResponse = builder.build();

      // Parse through the object to get the actual response for the first page of the input file.
      AnnotateImageResponse annotateImageResponse = annotateFileResponse.getResponses(0);

      // Here we print the full text from the first page.
      // The response contains more information:
      // annotation/pages/blocks/paragraphs/words/symbols
      // including confidence score and bounding boxes
      System.out.format("\nText: %s\n", annotateImageResponse.getFullTextAnnotation().getText());
    } else {
      System.out.println("No MATCH");
    }
  }
}```