开发者

Need help for a complex linq query

开发者 https://www.devze.com 2022-12-28 04:06 出处:网络
Ok so I\'ve got a DataTable here\'s the schema DataTable dt = new DataTable(); dt.Columns.Add(\"word\", typeof(string));

Ok so I've got a DataTable here's the schema

        DataTable dt = new DataTable();
        dt.Columns.Add("word", typeof(string));
        dt.Columns.Add("pronunciation", typeof(string));

The tabl开发者_开发知识库e is filled already and I'm trying to make a linq query so that i can output to the console or anywhere something like :

   Pronunciation : akses9~R => (list of words)

I want to output the pronunciations the most common and all the words that use it.


Something like this should give you what you want:

var results = dt.GroupBy(dr => dr.pronunciation);

foreach(var result in results)
{
    Console.Write("Pronunciation : {0} =>", result.Key);
    foreach(var word in result)
    {
        Console.Write("{0} ", word);
    }
    Console.WriteLine();
}

The GroupBy gives you an IGrouping whose Key property will contain the pronunciation and collection itself will contain all the words.


Sounds like you want a group by:

var q =
    from row in dt.Rows.Cast<DataRow>()
    let val = new { Word = (string)row["word"], Pronunciation = (string)row["pronunciation"] }
    group val by val.Pronunciation into g
    select g;

foreach (var group in q)
{
    Console.WriteLine(
    "Pronunciation : {0} => ({1})", 
    group.Key, 
    String.Join(", ", group.Select(x => x.Word).ToArray()));
}


var words = from row in table
            where row.pronunciation == "akses9~R"
            select row.word;
foreach (string word in words)
{
    Console.WriteLine(word);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消