簡體   English   中英

從C#或LINQ列表中過濾

[英]Filtering from list of C# or LINQ

我試圖從attachList過濾taxheaderID,它來自我的數據庫,其結構如此。

public int attachmentID { get; set; }
public int headerID { get; set; }
public string uploadedfilename { get; set; }
public string originalfilename { get; set; }
public string foldername { get; set; }

以下是從數據庫獲取數據的代碼:

public JsonResult GetAllAttach()
{
    using (car_monitoringEntities contextObj = new car_monitoringEntities())
    {
        var attachList = contextObj.car_taxcomputationattachment.ToList();
        return Json(attachList, JsonRequestBehavior.AllowGet);
    }
}

這些是我的嘗試:

attachList
    .Select(x => x.headerID)
    .Where(x => x == x)
    .Take(1);

和:

attachList = attachList
    .Where(al => attachList
        .Any(alx => al.taxheaderID == alx.headerID 
                 && al.headerID == alx.headerID));

問題是我想解析單個headerID上的多個附加或基於headerID過濾它們。 例如:

要修復的問題:

這是表格

期望的輸出: 組合

數據表: 數據表 數據表2

這是獲得輸出的實際解決方案,但我的同事告訴我,這不是一個好習慣,這就是為什么我試圖在函數本身中過濾它。 道歉,謝謝!

<div ng-repeat="att in attach|filter:{headerID:header.headerID}:true">

      <a href="~/UploadedFiles/{{att.uploadedfilename}}" download="{{att.uploadedfilename}}" target="_blank">{{att.uploadedfilename}} <br /></a>

 </div>

假設您有一個要在本地變量中過濾的標題ID,那么您幾乎是正確的

int headerIdToFind = 19;
// think of x as a local variable inside a foreach loop which
// iterates over each item in the attachList (it does not exist 
// outside the where method)
// this is what you got wrong when you compared the item to itself
var filteredAttach = attachList.Where(x => x.headerId = headerIdToFind);

// if you want to select only some properties based on header id
// you can use select to project those properties
var filteredAttach = attachList.Where(x => x.headerId = headerIdToFind).
                      Select(x => new {x.attachmentId, x.folderName});

// based on last image, you only want to select (project) header id and the 
// filename. so you do not need where (filter) at all
// you can put all the properties you need in the select clause
var filteredAttach = attachList.Select(x => new {x.headerId, x.attachmentId});
// you can enumerate the filtered attach list of convert it into a list 
var filteredAttach = filteredAttach.ToList();

通過Id獲取附件

public JsonResult GetAllAttach(int headerId)
{
    using (car_monitoringEntities contextObj = new car_monitoringEntities())
    {
        var attachList = contextObj.car_taxcomputationattachment
                                   .Where(x => x.headerID == headerId)
                                   .ToList();
        return Json(attachList, JsonRequestBehavior.AllowGet);
    }
}

如果要將所有數據放在一個JSON結果中,則需要創建嵌套視圖模型。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM