LINQ Group By where statement

本文关键字:statement where By Group LINQ | 更新日期: 2023-09-27 18:18:47

我在编写以下LINQ查询时遇到了麻烦。

ModelResponses集合有一个Attribute类型集合。我想选择具有唯一"Name"的modelresponse,它存储在Attributes集合中的一个元素中(在Attribute.Value中,Attribute.Id == 5)。

下面是我所拥有的,它似乎不起作用。我想我得到GroupBy()内部的逻辑不正确。

var test = deserialized.ModelResponses.
    GroupBy(
       x => x.Attributes.Where(attr => CasApiConversions.ToInt64(attr.Id) == 5).
           Select(y => new {y.Id, y.Value})
    ).Select(x => x.First()).ToList();

ModelResponse类:

public partial class ModelResponse
{
     [System.Xml.Serialization.XmlElementAttribute("attribute")]
     public Attribute[] Attributes { get; set; }
}

属性类:

public partial class Attribute
{
    [System.Xml.Serialization.XmlAttributeAttribute("id")]
    public string Id { get; set; }
    [System.Xml.Serialization.XmlTextAttribute()]
    public string[] Value { get; set; }
}

ModelResponse [0] .Attribute。值[0]= "MyModel"(其中Attribute为Attribute)。Id == 5)ModelResponse [1] .Attribute。值[0]= "MyModel"(其中Attribute为Attribute)。Id == 5)

我希望我的LINQ查询只给我自属性值以来的第一个ModelResponse。Id == 5在两个ModelResponse之间是相同的。

LINQ Group By where statement

你应该只有一个类

    public partial class ModelResponse
    {
        [System.Xml.Serialization.XmlAttributeAttribute("id")]
        public string Id { get; set; }
        [System.Xml.Serialization.XmlTextAttribute()]
        public string[] Value { get; set; }
    }
​
var SortByGroup = deserialized.ModelResponses.SelectAll(
       x => x.Attributes.Where(x=> CasApiConversions.ToInt64(x.Id) == 5).
           Select(y => new {y.Id, y.Value})
    ).Select(x => z.First()).ToList();

也许你需要试试

.ToList().Distinct()