0

天気がとても暑いので、私の脳はあまりうまく機能していません。LINQでこれを並べ替える最良の方法は何ですか?並べ替えは「C」に基づいて行われますが、「M」に適用されることに注意してください

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Compare
{
    public class M
    {
        public IList<C> Columns = new List<C>();
    }

    public class C
    {
        public bool SortByMe { get; set; }
        public string Guid { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            IList<M> list = new List<M>();

            M one = new M();
            one.Columns.Add(new C() 
            {
                SortByMe = true,
                Guid = "5"
            });
            one.Columns.Add(new C()
            {                
            });
            one.Columns.Add(new C()
            {             
            });

            M two = new M();
            two.Columns.Add(new C()
            {             
            });
            two.Columns.Add(new C()
            {
                SortByMe = true,
                Guid = "2"
            });
            two.Columns.Add(new C()
            {             
            });

            M three = new M();
            three.Columns.Add(new C()
            {

            });
            three.Columns.Add(new C()
            {
                SortByMe = true,
                Guid = "100"
            });
            three.Columns.Add(new C()
            {

            });

            list.Add(one);
            list.Add(two);
            list.Add(three);

            //Then sort the M by the occurrence of a C with SortByMe true.

        }
    }
}
4

2 に答える 2

1

つまり、各Mインスタンスには、そのコレクションの中で、プロパティが;である単一のインスタンスがあります。 これらの要素の値でインスタンスのコレクションを並べ替えたいですか?CColumnsSortByMetrueMGUIDC

list = list.OrderBy(m => m.Columns.Single(c => c.SortByMe).Guid).ToList();

GUIDであるため、並べ替えは数字ではなくstringアルファベット(、、)になることに"100"注意してください。数値にしたい場合は、をスローする必要があります。"2""5"int.Parse

編集:数値ソートを実行するバージョン:

list = list.OrderBy(m => int.Parse(m.Columns.Single(c => c.SortByMe).Guid)).ToList();

そして論理的に同等のクエリ構文:

list =
(
    from m in list
    orderby
    (
        from c in m.Columns
        where c.SortByMe
        select int.Parse(c.Guid)
    ).Single()
    select m
).ToList();

に設定されている特定のコレクションC内の複数の要素や、有効な整数ではない値など、元の仮定に失敗すると、式全体が失敗することを考慮する必要があります。ColumnsSortByMetrueGUID

于 2012-05-24T18:43:17.123 に答える
1
        var query = from m in list
                    let c = m.First(x => x.SortByMe)
                    orderby c.Guid
                    select m;
于 2012-05-24T18:44:17.173 に答える