Linq查询使用来自另一列的条件的多个列值进行计数

时间:2018-02-23 07:33:08

标签: c# linq

我有一张表A如下:

表A

ID  ScheduleID     UserCode

1        4              D
2        4              A  
3        1              B   
4        2              D  
5        4              C   
6        6              A    
7        2              B

我想获取与特定UserCode对应的所有那些scheduleID值的行数。例如,对于UserCode = D,相应的ScheduleID是4& 2. ScheduleID = 2&的所有行的计数。 4是5。

我尝试过以下查询:

int count = A.Count(j => j.ScheduleID.Equals  
   (A.Any(k => k.UserCode == D)));

这会产生运行时错误

  

"无法转换类型' System.Boolean'输入' System.Object'

。任何人都可以建议这个场景应该是什么样的准确查询?

2 个答案:

答案 0 :(得分:2)

var query = A.Where(p=> p.UserCode == D).Select(x=> x.ScheduleID);
var count = A.Count(p=> query.Contains(p.ScheduleID));

你可以在第二行替换查询可能与顶行,使其成为一行,但我个人认为这是更清洁

答案 1 :(得分:2)

这是我获得相同结果的解决方案:

func loadHtmlContent() {

    let articleHtmlData = "<head><style>img{width:300px !important;height:225px !important}</style></head>"+articleContent

    do {
        let attrStr = try NSMutableAttributedString(
            data: articleHtmlData.data(using: String.Encoding.unicode, allowLossyConversion: true)!,
            options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
            documentAttributes: nil)

        attrStr.enumerateAttribute(
            NSFontAttributeName,
            in:NSMakeRange(0,attrStr.length),
            options:.longestEffectiveRangeNotRequired) { value, range, stop in
                let f1 = value as! UIFont
                let f2 = UIFont(name:"Helvetica", size:20)!
                if let f3 = applyTraitsFromFont(f1, to:f2) {
                    attrStr.addAttribute(
                        NSFontAttributeName, value:f3, range:range)
                }
        }

        self.articleHeight = self.heightForHtmlString(attrStr)
        self.articleContentTextView.attributedText = attrStr

    } catch let error {
        print(error)
    }

}

func heightForHtmlString(_ text: NSAttributedString) -> CGFloat {
    let label:UILabel = UILabel.init(frame: CGRect.init(x: 0, y: 0, width: UIScreen.main.bounds.size.width-(16*4), height: CGFloat.greatestFiniteMagnitude))
    label.numberOfLines = 0
    label.lineBreakMode = NSLineBreakMode.byWordWrapping
    label.font = UIFont(name: "PingFangTC-Regular", size: 20.0)
    label.attributedText = text
    label.sizeToFit()
    return label.frame.height
}