LINQ to dataSet:如何在一个order之后抓取两列

时间:2011-06-20 06:39:21

标签: linq

我有以下架构:

  

TierId,CountryCode,CountryName

如何使用LINQ获取Enumerable集合 (TierId ,,)

我知道我可以做以下解决方案,但有没有办法避免双重排序? 通过col3命令col1和col2(粘在一起)之类的东西?

 var a = from row in ds.Tables[1].AsEnumerable()
         group row["CountryCode"] by row["TierId"]
         into countrieCodes
         select new
             {
                 tierId = Convert.ToInt32(countrieCodes.Key)-1,
                 countrieCodesList = countrieCodes.Select(i => i.ToString()).ToList()
              };

 var b = from row in ds.Tables[1].AsEnumerable()
         group row["CountryName"] by row["TierId"]
         into countrieNames
         select new
         {
            tierId = Convert.ToInt32(countrieNames.Key)-1,
            countrieCodesList = countrieNames.Select(i => i.ToString()).ToList()
         };

var c = from itemA in a
        from itemB in b
        where itemA.tierId == itemB.tierId
        orderby itemA.tierId
        select new {
          TierId = itemA.tierId,
          CountriesA = itemA.countrieCodesList,
          CountriesB = itemA.countrieCodesList,
         };

由于

1 个答案:

答案 0 :(得分:0)

嗯,我不知道。试图将内容输入Linq并不总是最易读的方法。替代方法如何:

   class TierCountries
   {
       int TierId { get; private set }
       public HashSet<string> CountryCodes { get; private set; }
       public HashSet<string> CountryNames { get; private set; }

       public TierCountries(int tierId)
       {
            TierId = tierId;
            CountryCodes = new HashSet<string>();
            CountryNames = new HashSet<string>();
       }
   }

   var _TierCountryMap = new Dictionary<int, TierCountries>();

   foreach (var row in ds.Tables[1].AsEnumerable())
   {
       int tierId = Convert.ToInt32(row["TierId"]);
       TierCountries tc;
       if (!_TierCountryMap.TryGet(tierId, out tc))
       {
            tc = new TierCountries(tierId);
            _TierCountryMap[tierId] = tc;
       }
       tc.CountryCodes.Add(row["CountryCode"]);
       tc.CountryNames.Add(row["CountryName"]);
   }

Linq并不多,但只有一次超过桌面。