将变量插入列表c#

时间:2013-11-14 15:50:21

标签: c# visual-studio

基本上这是我在数据层中的代码。我刚从最后一行代码中遇到问题。我试图将变量'distinctIdsWoring'插入到promoCodeValues列表中,但是我收到了错误。

    public static List<PromotionalCodeValue> GetPromotionalCodeValues(string Platform)
    {
        SqlConnection conn = xxxConnection();
        SqlCommand comm = new SqlCommand("GetPromotionalCodeValues", conn);
        comm.CommandType = CommandType.StoredProcedure;

        comm.Parameters.AddWithValue("@Platform", Platform);

        conn.Open();

        List<PromotionalCodeValue> promoCodeValues = new List<PromotionalCodeValue>();

        try
        {
            SqlDataReader dataReader = comm.ExecuteReader();

            while (dataReader.Read())
            {
                promoCodeValues.Add(new PromotionalCodeValue(dataReader));
            }
        }
        finally
        {
            conn.Close();
        }

        promoCodeValues.Clear();

        var distinctIdsWorking = promoCodeValues.AsEnumerable()
                .Select(s => new
                {
                    id = s.Value,
                })
                .Distinct().ToList();

        promoCodeValues = distinctIdsWorking; //????????????????????????????

        return promoCodeValues;

    }

感谢

5 个答案:

答案 0 :(得分:3)

您要将distinctIdsWorking分配给具有不兼容类型的promoCodeValues

请尝试使用DistinctIEqualityComparer重载。

public class PromotionalCodeEqualityComparer
    : IEqualityComparer<PromotionalCodeValue>
{
    public bool Equals(PromotionalCodeValue x, PromotionalCodeValue y)
    {
        return x.Value == y.Value;
    }

    public int GetHashCode(PromotionalCodeValue obj)
    {
        return obj.Value != null ? obj.Value.GetHashCode() : 0;
    }
}

用法:

var distinctIdsWorking = promoCodeValues.Distinct(new PromotionalCodeEqualityComparer());

return distinctIdsWorking;

您还要清除promoCodeValues,它将不会返回任何内容而您会丢失using个语句。

修正:

var promoCodeValues = new List<PromotionalCodeValue>();

using(var connection = xxxConnection())
using(var command = new SqlCommand("GetPromotionalCodeValues", connection))
{
    command.CommandType = CommandType.StoredProcedure;
    command.Parameters.AddWithValue("@Platform", Platform);

    connection.Open();

    using(var reader = command.ExecuteReader())
    {
        while (reader.Read())
        {
            promoCodeValues.Add(new PromotionalCodeValue(reader));
        }
    }
}

return promoCodeValues.Distinct(new PromotionalCodeEqualityComparer()).ToList();

答案 1 :(得分:2)

distinctIdsWorking不是List<PromotionalCodeValue>,因此您无法将其分配给promoCodeValues

看起来您正在尝试确保在结果中每个ID只能获得一个促销代码。尝试这样的事情:

public static List<PromotionalCodeValue> GetPromotionalCodeValues(string Platform)
{
    // This ensures that your connection gets closed even if there's
    // an exception thrown. No need for a try/finally
    using (SqlConnection conn = xxxConnection())
    {
        SqlCommand comm = new SqlCommand("GetPromotionalCodeValues", conn);
        comm.CommandType = CommandType.StoredProcedure;

        comm.Parameters.AddWithValue("@Platform", Platform);

        conn.Open();

        List<PromotionalCodeValue> promoCodeValues = new List<PromotionalCodeValue>();

        SqlDataReader dataReader = comm.ExecuteReader();

        while (dataReader.Read())
        {
            promoCodeValues.Add(new PromotionalCodeValue(dataReader));
        }

        promoCodeValues = 
            (from pc in promoCodeValues
            // Group by ID, then choose the first item from each group;
            // This is effectively the same as "DistinctBy" but requires
            // no extra methods or classes.
            group pc by pc.Value into g
            select g.First())
                .ToList();

        return promoCodeValues;
    }
}

答案 2 :(得分:2)

您正在使用promoCodeValues.Clear();清除列表,因此distinctIdsWorking始终为空列表,但不包含任何元素。

答案 3 :(得分:1)

为简化此操作,首先构建一个相等比较器:

public class PromotionalCodeValueEqualityComparer :
    IEqualityComparer<PromotionalCodeValue>
{
    public bool Equals(PromotionalCodeValue x, PromotionalCodeValue y)
    {
        return x.Value == y.Value;
    }

    public int GetHashCode(PromotionalCodeValue x)
    {
        return x.Value.GetHashCode();
    }
}

然后你可以这样做:

return promoCodeValues.Distinct(new PromotionalCodeValueEqualityComparer());

答案 4 :(得分:1)

var distinctIdsWorking = promoCodeValues.AsEnumerable()                     。选择(s =&gt; new                     {                         id = s.Value,                     })                     。.Distinct()ToList();

仔细观察:通过Select(s => new { id = s.Value })语句生成只有ID字段的匿名对象,之后不是之前的类(PromotionalCodeValue)。

您需要安装MoreLINQ软件包或从该框架中删除此代码扩展程序:

public static IEnumerable<TSource> DistinctBy<TSource, TKey> (this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
{
    HashSet<TKey> seenKeys = new HashSet<TKey>();
    foreach (TSource element in source)
    {
        if (seenKeys.Add(keySelector(element)))
        {
            yield return element;
        }
    }
}

并使用此功能:DistinctBy(x => x.ID)或者如果您需要多个密钥:DistinctBy(x => { x.ID, x.Name })

所以你可以重写你的代码: var distinctIdsWorking = promoCodeValues.AsEnumerable().DistinctBy(code => code.Value).ToList();