需要有关复杂linq查询的帮助

时间:2010-04-27 19:52:23

标签: c# .net linq datatable

好的,我这里有一个DataTable架构

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

表已经填满了,我正在尝试创建一个linq查询,以便我可以输出到控制台或任何类似的地方:

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

我想输出最常见的发音和使用它的所有单词。

3 个答案:

答案 0 :(得分:2)

这样的东西可以给你你想要的东西:

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();
}

GroupBy为您提供一个IGrouping,其Key属性将包含发音,而集合本身将包含所有单词。

答案 1 :(得分:1)

听起来你想要一个小组:

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()));
}

答案 2 :(得分:0)

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