如何从Tupled List中获取第一个元素
本文关键字:获取 第一个 元素 List Tupled | 更新日期: 2023-09-27 17:59:50
我有一个列表,即
var d = new List<Tuple<string, double>>();
用于以下代码:
var d = new List<Tuple<string, double>>();
while ((line = file.ReadLine()) != null)
{
d.Add(Tuple.Create(line, p.calculate_CS(line, document)));
}
System.IO.StreamWriter fileW = new System.IO.StreamWriter(@"C:'Users'Malik'Desktop'write_research_fields_temp.txt");
foreach (var item in d.OrderByDescending(t => t.Item2))
{
fileW.WriteLine("{0} - {1}", item.Item2, item.Item1);
}
我想将排序(降序)列表的第一个元素(只有字符串值而不是双值)存储在一个字符串中,即string top_value
任何建议都将不胜感激。感谢
var dd = new List<Tuple<string, double, string>>();
while ((line = file.ReadLine()) != null)
{
dd.Add(Tuple.Create(line, p.calculate_CS(line, document), document));
}
var top_value = dd.OrderByDescending(x => x.Item2).FirstOrDefault();
if (top_value != null)
{
// look up record using top_value.Item3, and then store top_value.Item1
var abstrct = top_value.Item3.ToString();
var r_field = top_value.Item1.ToString();
write_To_Database(abstrct, r_field);
}
这是将数据插入数据库的插入方法。
static void write_To_Database(string document, string research_field)
{
try
{
SqlConnection con = new SqlConnection("Data Source=KHIZER;Initial Catalog=subset_aminer;Integrated Security=True;");
con.Open();
SqlCommand query = con.CreateCommand();
query.CommandText = "select id from sub_aminer_paper where pid between 1 and 500 and DATALENGTH(p_abstract) != 0 and p_abstract = " + document;
SqlDataReader reader = query.ExecuteReader();
reader.Read();
int id = reader.GetInt32(0);
//reader.Close();
query.Parameters.Add("@research_field", SqlDbType.Text);
query.Parameters.Add("@id", SqlDbType.Int);
query.CommandText = "insert into sub_aminer_paper (research_area) values(@research_field) where id = @id";
query.ExecuteNonQuery();
con.Close();
}
catch (Exception e)
{
Console.WriteLine("Exception: " + e.Message);
}
finally
{
Console.WriteLine("Executing finally block.");
}
}
有什么建议吗?
只需使用一点LINQ对集合进行排序并获取所需的结果。
这是根据您的数值(顶部最大)排序,然后获取与其配对的第一个字符串值:
string top_value = d.OrderByDescending(x => x.Item2)
.Select(x => x.Item1)
.FirstOrDefault();
在您现有的代码中,不需要迭代所有结果来获得第一个结果,所以您基本上可以这样做:
foreach (var item in d.OrderByDescending(t => t.Item2))
{
string top_value = item.Item1;
... // do stuff
break;
}
但这有点傻,所以你可以消除这个循环:
var orderedItems = d.OrderByDescending(t => t.Item2);
var largestItem = d.FirstOrDefault(); // covers the case where the list is empty
string top_value = largestItem != null ? largestItem.Item1 : null;
就我个人而言,我更喜欢LINQ,但YMMV。:)
至于将其存储在数据库中,在创建元组时,看起来会丢失document
的值。我只需要更改Tuple来存储文档,并稍微修改LINQ语句:
var d = new List<Tuple<string, double, string>>();
while ((line = file.ReadLine()) != null)
{
d.Add(Tuple.Create(line, p.calculate_CS(line, document), document));
}
var top_value = d.OrderByDescending(x => x.Item2)
.FirstOrDefault();
if (top_value != null)
{
// look up record using top_value.Item3, and then store top_value.Item1
}