2012-02-26 14 views
7

問題の継続How get array in linq to entity?linqからエンティティへの受信辞書<int, string>?今

ではなく、ある配列=>辞書 市タイプは辞書

var sites = (from country in db.Countries 
         select new 
         { 
          Country = country.Title, 
          Cities = country.Cities.Select(m => m.Title) 
         }) 
         .AsEnumerable() 
         .Select(country => new SitiesViewByUser() 
         { 
          Country = country.Country, 
          City = country.Cities.ToArray() 
         }); 

アップデートです:あなたはから辞書を作成するためにToDictionaryを使用することができます

public class SitiesViewByUser 
    { 
     public string Country { get; set; } 
     public Dictionary<int, string> City { get; set; } 
    } 
+0

SitiesViewByUserのCityプロパティの定義は何ですか? – devdigital

+0

私の投稿を更新します – Mediator

+0

ディクショナリのintキーはどこから来たのですか?これは街の主要なキーですか?最初のLINQ to Entitiesクエリでこれを取得していません。 – devdigital

答えて

9

LINQシーケンス。

最初の部分はキーで、2番目の部分は値です。

.Select(country => new SitiesViewByUser() 
{ 
    Country = country.Country, 
    City = country.Cities.ToDictionary(c => c, c => c); 
}); 

これはDictionary<string, string>

あなたのLINQはいえ、非常に混乱していてSitiesViewByUserCityが定義されていることを前提としています。あなたはCountryの形になると仮定して匿名型を作成していますが、それにはCountryというプロパティがあり、実際にはその国のTitle(それは国名ですか?)です。

Titlesのコレクションもありますので、SitiesViewByUserタイプのCity辞書にどのような価値を使用するかわかりません。

また、Sitieとは何ですか? :\

更新

あなたはこのような何か行うことができます:なぜあなたがするSitiesViewByUserタイプを変更しないでください、また

var countries = (from country in db.Countries 
    select new 
    { 
    Title = country.Title, 
    CityIds = country.Cities.Select(c => c.Id), 
    CityTitles = country.Cities.Select(c => c.Title) 
    }).AsEnumerable(); 

// You have a collection of anonymous types at this point, 
// each type representing a country 
// You could use a foreach loop to generate a collection 
// of SitiesViewByUser, or you could use LINQ: 

var sitiesViewByUsers = countries.Select(c => new SitiesViewByUser 
    { 
     Country = c.Title, 
     City = c.CityIds.Zip(c.CityTitles, (k, v) => new { Key = k, Value = v }) 
       .ToDictionary(x => x.Key, x => x.Value) 
    }; 

を:

public class SitiesViewByUser 
{ 
    public string Country { get; set; } 
    public IEnumerable<City> Cities { get; set; } 
} 

その後、あなたはできます(流暢な構文を使用して):

var sitiesViewByUsers = db.Countries.Select(c => new SitiesViewByUser 
    { 
    Country = c.Title, 
    Cities = c.Cities 
    }); 
+0

私の投稿を更新しました – Mediator

関連する問題