【问题标题】:After getting distinct list, using the results in a query获得不同的列表后,在查询中使用结果
【发布时间】:2019-03-29 18:06:17
【问题描述】:

我最初获得了从具有多个节点进行分组的较大列表中获取不同列表的帮助。我认为这行得通。

我现在需要有关如何使用该列表的帮助。

这是我的代码:

var LOE = results.Body
                 .getEntitiesResponse
                 .getEntities
                 .listOfEntities
                 .Select(x=>new string[]{x.entityIdentification.DUNS,x.entityIdentification.DUNSPlus4})
                 .Distinct();

foreach (var d in LOE)
{
    using (OleDbConnection conn = new OleDbConnection(cm.ConnectionString))
    {
        using (OleDbCommand cmd = new OleDbCommand())
        {
            cmd.CommandText = "sam.DeleteRecordsToBeUpdated";
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@a", d.DUNS);  //This is my problem area
            cmd.Parameters.AddWithValue("@b", d.DUNSPlus4); //This is my problem area
            cmd.Connection = conn;

            conn.Open();
            cmd.ExecuteNonQuery();
        }
    }
}

有人可以帮我了解如何使用第一行中创建的新对象吗?

也许我没有正确设置第一行?我似乎无法像尝试那样使用该对象。

【问题讨论】:

标签: c# linq


【解决方案1】:

您的问题在于第一条语句

var LOE = results.Body.getEntitiesResponse.getEntities.listOfEntities
          .Select(x=>new string[]{x.entityIdentification.DUNS,x.entityIdentification.DUNSPlus4})
          .Distinct();

你应该像下面这样

var LOE = results.Body.getEntitiesResponse.getEntities.listOfEntities
            .Select(x => new {
                x.entityIdentification.DUNS,
                x.entityIdentification.DUNSPlus4
            }).Distinct();

在您的情况下,您选择的是数组,而不是匿名类

【讨论】:

    【解决方案2】:

    您可以创建一个类来将值映射到:

    public class DunsMapping()
    {
        public string Duns { get; set; }
        public string DunsPlus4 { get; set; }
    
        public DunsMapping(string duns, string duns4)
        {
            Duns = duns;
            DunsPlus4 = duns4;
        }
    }
    

    那么 linq 会变成:

    var LOE = results.Body
                 .getEntitiesResponse
                 .getEntities
                 .listOfEntities
                 .Select(x=>new DunsMapping(x.entityIdentification.DUNS,
                                            x.entityIdentification.DUNSPlus4))
                 .Distinct();
    

    或者,如果您需要返回不同实体的列表,您可以使用GroupBy

    var LOE = results.Body
                 .getEntitiesResponse
                 .getEntities
                 .listOfEntities
                 .GroupBy(g => new { g.DUNS, g.DUNSPlus4 })
                 .Select(g => g.First());
    

    这将返回IEnumerable<YourEntity>

    【讨论】:

    • 你测试了吗?我认为它不会起作用,因为您没有在 DunsMapping 类中定义 EqualsGetHashCode
    • 哦,为了Distinct()?你可能是对的......我现在就测试
    • @AleksAndreev 我测试了它确实有效,但无论如何更新了答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-06
    • 1970-01-01
    • 2020-10-13
    • 2013-05-06
    相关资源
    最近更新 更多