0

いくつかの製品を保管するテーブルがあります。

ProductA
ProductB
ProductC

リクエストの 1 つは、1 つの製品が別の製品に属することができるということです。

ProductA
ProductD -> ProductA
ProductE -> ProductA
ProductB
ProductF -> ProductB
ProductC

ご覧のとおり、別の製品に属する製品はそのすぐ下に配置する必要があります。1 つのグリッドにのみデータを表示する必要があるため、すべてのデータは 1 つのリスト (ネストされたコレクションではない) に属している必要があります。

別の製品を指す新しいプロパティ ReferenceProductId を導入すると、「所属」の問題は解決しますが、それらを並べ替える方法が見つかりません。ProductA は ProductA に属すると言えれば簡単な方法ですが、私が間違っていなければ、それは不可能です。また、ある製品を別の製品に割り当てる場合、次のことはできません。

product.ReferenceProductId = anotherProduct.Id

ID主キーを使用しているため、参照自体を割り当てる必要があるため、新しいレコードのIDは0になります。

product.ReferenceProduct = anotherProduct;

ここであなたの考えは何ですか?データを正しく保存することはできますが、上記のソート順でデータをロードすることはできません。

4

1 に答える 1

2

リストを並べ替えるカスタム比較子を作成できます。これは単なる例ですが、製品参照がない場合に referenceId が null であると仮定して、ID と参照 ID を比較することで、上記の結果を得ることができました。を呼び出して FK が更新されていない場合はコードを変更できますproduct.Reference.Idが、簡単にするためにこれを無視しました。

私の製品クラス:

    public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int? ReferenceId { get; set; }
    }

比較者:

public class ProductComparer : IComparer<Product>
{
    public int Compare(Product product, Product other)
    {
        if (product.ReferenceId == null && other.ReferenceId == null)
            return product.Id.CompareTo(other.Id);

        if (product.ReferenceId == null && other.ReferenceId != null)
            return product.Id.CompareTo(other.ReferenceId);

        if (product.ReferenceId != null && other.ReferenceId == null)
            return ((int) product.ReferenceId).CompareTo(other.Id);

        if (product.ReferenceId == other.ReferenceId)
            return product.Id.CompareTo(other.Id);

        return ((int) product.ReferenceId).CompareTo((int) other.ReferenceId);
    }
}

次に、次のような方法でコレクションを呼び出します。

products.OrderBy(p => p, new ProductComparer());
于 2012-08-15T15:41:56.023 に答える