在 c# 或 vb.net 如何使用 LINQ 统计 Dictionary 中符合条件的对象数量

在 c# 或 vb.net 如何使用 LINQ 统计 Dictionary 中符合条件的对象数量,第1张

见以下示例

using System;

using SystemCollectionsGeneric;

using SystemLinq;

namespace MyApplication

{

    class Program

    {

        public class MyClass

        {

            public string Name { get; set; }

            public bool IsTrue { get; set; }

        }

        static void Main(string[] args)

        {

            Dictionary<int, MyClass> dic =

                new Dictionary<int, MyClass>();

            //添加

            dicAdd(1, new MyClass { Name = "张三", IsTrue = false });

            dicAdd(2, new MyClass { Name = "张四", IsTrue = true });

            dicAdd(3, new MyClass { Name = "张五", IsTrue = false });

            dicAdd(4, new MyClass { Name = "张六", IsTrue = true });

            dicAdd(5, new MyClass { Name = "张七", IsTrue = false });

            int c1 = dicCount(e => eValueIsTrue == true);

            ConsoleWriteLine(c1);  //输出2

            int c2 = dicCount(e => eValueIsTrue == false);

            ConsoleWriteLine(c2);  //输出3

            

            // 或者    

            var qry1 = from x in dic

                      where xValueIsTrue == true

                      select x;

            int c3 = qry1Count();

            ConsoleWriteLine(c3); //输出2

            var qry2 = from x in dic

                      where xValueIsTrue == false

                      select x;

            int c4 = qry2Count();   //输出3

            ConsoleWriteLine(c4);

        }

    }

}

取这串字符串中最大的数字?

string k = "abcdefghijklmnopsadjlvas094i029340$#%#&^%%$000888";

var max =kAsQueryable()Where(o => o >= 48 && o <= 57)Max();

console?

int h=10;

for(int i=1;i<=h;i++)

{

       ConsoleWriteLine(“”padleft(i,''));

for(int i=h-1;i>0;i--)

{

       ConsoleWriteLine(“”padleft(i,''));

}

storeDBAlbumsOrderByDescending(a => aOrderDetailsCount())Take(count)ToList();

数据上下文Albums数据表倒序排序(条件为按照各数据关联的OrderDetails数据表中数据的条数)拿记录(count条)立即执行转为list

使用join来连接

EnumerableJoin<TOuter, TInner, TKey, TResult> 方法 (IEnumerable<TOuter>, IEnumerable<TInner>, Func<TOuter, TKey>, Func<TInner, TKey>, Func<TOuter, TInner, TResult>)

发送反馈

基于匹配键对两个序列元素进行关联。

使用默认的相等比较器对键进行比较。

命名空间: SystemLinq

程序集: SystemCore(在 SystemCoredll 中)

语法

--------------------------------------------------------------------------------

VBC#C++F#JScript以带有颜色区分的格式查看复制到剪贴板打印<ExtensionAttribute> _

Public Shared Function Join(Of TOuter, TInner, TKey, TResult) ( _

outer As IEnumerable(Of TOuter), _

inner As IEnumerable(Of TInner), _

outerKeySelector As Func(Of TOuter, TKey), _

innerKeySelector As Func(Of TInner, TKey), _

resultSelector As Func(Of TOuter, TInner, TResult) _

) As IEnumerable(Of TResult)

<ExtensionAttribute> _

Public Shared Function Join(Of TOuter, TInner, TKey, TResult) ( _

outer As IEnumerable(Of TOuter), _

inner As IEnumerable(Of TInner), _

outerKeySelector As Func(Of TOuter, TKey), _

innerKeySelector As Func(Of TInner, TKey), _

resultSelector As Func(Of TOuter, TInner, TResult) _

) As IEnumerable(Of TResult)

public static IEnumerable<TResult> Join<TOuter, TInner, TKey, TResult>(

this IEnumerable<TOuter> outer,

IEnumerable<TInner> inner,

Func<TOuter, TKey> outerKeySelector,

Func<TInner, TKey> innerKeySelector,

Func<TOuter, TInner, TResult> resultSelector

)

public static IEnumerable<TResult> Join<TOuter, TInner, TKey, TResult>(

this IEnumerable<TOuter> outer,

IEnumerable<TInner> inner,

Func<TOuter, TKey> outerKeySelector,

Func<TInner, TKey> innerKeySelector,

Func<TOuter, TInner, TResult> resultSelector

)

[ExtensionAttribute]

public:

generic<typename TOuter, typename TInner, typename TKey, typename TResult>

static IEnumerable<TResult>^ Join(

IEnumerable<TOuter>^ outer,

IEnumerable<TInner>^ inner,

Func<TOuter, TKey>^ outerKeySelector,

Func<TInner, TKey>^ innerKeySelector,

Func<TOuter, TInner, TResult>^ resultSelector

)

[ExtensionAttribute]

public:

generic<typename TOuter, typename TInner, typename TKey, typename TResult>

static IEnumerable<TResult>^ Join(

IEnumerable<TOuter>^ outer,

IEnumerable<TInner>^ inner,

Func<TOuter, TKey>^ outerKeySelector,

Func<TInner, TKey>^ innerKeySelector,

Func<TOuter, TInner, TResult>^ resultSelector

)

static member Join :

outer:IEnumerable<'TOuter>

inner:IEnumerable<'TInner>

outerKeySelector:Func<'TOuter, 'TKey>

innerKeySelector:Func<'TInner, 'TKey>

resultSelector:Func<'TOuter, 'TInner, 'TResult> -> IEnumerable<'TResult>

static member Join :

outer:IEnumerable<'TOuter>

inner:IEnumerable<'TInner>

outerKeySelector:Func<'TOuter, 'TKey>

innerKeySelector:Func<'TInner, 'TKey>

resultSelector:Func<'TOuter, 'TInner, 'TResult> -> IEnumerable<'TResult>

类型参数

TOuter

第一个序列中的元素的类型。

TInner

第二个序列中的元素的类型。

TKey

键选择器函数返回的键的类型。

TResult

结果元素的类型。

参数

outer

类型: SystemCollectionsGenericIEnumerable <TOuter>

要联接的第一个序列。

inner

类型: SystemCollectionsGenericIEnumerable <TInner>

要与第一个序列联接的序列。

outerKeySelector

类型: SystemFunc <TOuter, TKey>

用于从第一个序列的每个元素提取联接键的函数。

innerKeySelector

类型: SystemFunc <TInner, TKey>

用于从第二个序列的每个元素提取联接键的函数。

resultSelector

类型: SystemFunc <TOuter, TInner, TResult>

用于从两个匹配元素创建结果元素的函数。

返回值

类型: SystemCollectionsGenericIEnumerable <TResult>

一个具有 TResult 类型元素的 IEnumerable<T>,这些元素是通过对两个序列执行内部联接得来的。

使用说明

在 Visual Basic 和 C# 中,可以在 IEnumerable<TOuter> 类型的任何对象上将此方法作为实例方法来调用。当使用实例方法语法调用此方法时,请省略第一个参数。有关更多信息,请参见 扩展方法 (Visual Basic)或 扩展方法(C# 编程指南)。

异常

--------------------------------------------------------------------------------

异常 条件

ArgumentNullException

outer 或 inner 或 outerKeySelector 或 innerKeySelector 或 resultSelector 为 null。

备注

--------------------------------------------------------------------------------

此方法通过使用延迟执行实现。

即时返回值为一个对象,该对象存储执行 *** 作所需的所有信息。

只有通过直接调用对象的 GetEnumerator 方法或使用 Visual C# 中的 foreach(或 Visual Basic 中的 For Each)来枚举该对象时,才执行此方法表示的查询。

使用默认的相等比较器 Default 对键进行哈希处理和比较。

联接是指基于某个公共键使两个信息源的元素相关联的 *** 作。

Join 在一个方法调用中产生两个信息源和使它们相匹配的密钥。

这与 SelectMany 的用法不同,后者需要一个以上的方法调用才可以执行相同的 *** 作。

Join 保留 outer 中的元素的顺序,并且对于这些元素中的每一个元素,保留 inner 中的匹配元素的顺序。

在查询表达式语法中, join (Visual C#) 或 Join (Visual Basic) 子句转换为 Join 的一个调用。

在关系数据库术语中, Join 方法实现内部同等联接。'

“内部”表示结果中仅包含在另一序列中具有匹配项的元素。

“同等联接”是在其中比较键是否相等的联接。

左外部联接 *** 作没有专用的标准查询运算符,但可以使用 GroupJoin 方法执行此 *** 作。

请参见 联接运算。

示例

--------------------------------------------------------------------------------

下面的代码示例演示如何使用 Join<TOuter, TInner, TKey, TResult>(IEnumerable<TOuter>, IEnumerable<TInner>, Func<TOuter, TKey>, Func<TInner, TKey>, Func<TOuter, TInner, TResult>) 基于公共键对两个序列执行内部联接。

VBC#C++F#JScript以带有颜色区分的格式查看复制到剪贴板打印Structure Person

Public Name As String

End Structure

Structure Pet

Public Name As String

Public Owner As Person

End Structure

Sub JoinEx1()

Dim magnus As New Person With {Name = "Hedlund, Magnus"}

Dim terry As New Person With {Name = "Adams, Terry"}

Dim charlotte As New Person With {Name = "Weiss, Charlotte"}

Dim barley As New Pet With {Name = "Barley", Owner = terry}

Dim boots As New Pet With {Name = "Boots", Owner = terry}

Dim whiskers As New Pet With {Name = "Whiskers", Owner = charlotte}

Dim daisy As New Pet With {Name = "Daisy", Owner = magnus}

Dim people As New List(Of Person)(New Person() {magnus, terry, charlotte})

Dim pets As New List(Of Pet)(New Pet() {barley, boots, whiskers, daisy})

' Create a list of Person-Pet pairs, where each element is an

' anonymous type that contains a Pet's name and the name of the

' Person that owns the Pet

Dim query = _

peopleJoin(pets, _

Function(person) person, _

Function(pet) petOwner, _

Function(person, pet) _

New With {OwnerName = personName, Pet = petName})

Dim output As New SystemTextStringBuilder

For Each obj In query

outputAppendLine(objOwnerName & " - " & objPet)

Next

' Display the output

MsgBox(outputToString)

End Sub

' This code produces the following output:

'

' Hedlund, Magnus - Daisy

' Adams, Terry - Barley

' Adams, Terry - Boots

' Weiss, Charlotte - Whiskers

Structure Person

Public Name As String

End Structure

Structure Pet

Public Name As String

Public Owner As Person

End Structure

Sub JoinEx1()

Dim magnus As New Person With {Name = "Hedlund, Magnus"}

Dim terry As New Person With {Name = "Adams, Terry"}

Dim charlotte As New Person With {Name = "Weiss, Charlotte"}

Dim barley As New Pet With {Name = "Barley", Owner = terry}

Dim boots As New Pet With {Name = "Boots", Owner = terry}

Dim whiskers As New Pet With {Name = "Whiskers", Owner = charlotte}

Dim daisy As New Pet With {Name = "Daisy", Owner = magnus}

Dim people As New List(Of Person)(New Person() {magnus, terry, charlotte})

Dim pets As New List(Of Pet)(New Pet() {barley, boots, whiskers, daisy})

' Create a list of Person-Pet pairs, where each element is an

' anonymous type that contains a Pet's name and the name of the

' Person that owns the Pet

Dim query = _

peopleJoin(pets, _

Function(person) person, _

Function(pet) petOwner, _

Function(person, pet) _

New With {OwnerName = personName, Pet = petName})

Dim output As New SystemTextStringBuilder

For Each obj In query

outputAppendLine(objOwnerName & " - " & objPet)

Next

' Display the output

MsgBox(outputToString)

End Sub

' This code produces the following output:

'

' Hedlund, Magnus - Daisy

' Adams, Terry - Barley

' Adams, Terry - Boots

' Weiss, Charlotte - Whiskers

帅哥的意思是想从数据库中选取一字段,然后单击button后就将选出的数据填充到listbox控件里头是不?

如果是的话我建议公共方法那里返回dataset,然后用for循环添加到listbox里头,举个例子吧:

公共方法这样写:

public DataSet sql_dataset(string str_command,string str_tablename)//返回数据集对象,参数为查询语句和表名

{

myconnectionOpen();DataSet myset = new DataSet();

myadapter = new SqlDataAdapter(str_command, myconnection);

mysetClear();

mysetReset();

myadapterFill(myset, str_tablename);

myconnectionClose();

return myset;

}

然后button的事件处理方法里头可以这样调用:

private void button1_Click(object sender, EventArgs e)

{

string str_select = "select from Message_list";

DataSet myset=new DataSet();//声明一个新的数据集接收返回的数据集

myset = cdsql_dataset(str_select, "Message_list");

int i = mysetTables[0]RowsCount;//记录总行数

ListBox1Itemsclear();//清空以前选项

for (int i2 = 0; i2 < i; i2++)

{

thisListBox1ItemsAdd(mysetTables[0]Rows[i2][0]ToString());

}

}

using System;

using SystemCollectionsGeneric;

using SystemLinq;

using SystemText;

using MicrosoftOfficeInteropExcel;

using SystemData;

namespace ExcelTest

{

public class ExcelUtil

{

SystemDataDataTable table11 = new SystemDataDataTable();

public void ExportToExcel(SystemDataDataTable table, string saveFileName)

{

bool fileSaved = false;

//ExcelApp xlApp = new ExcelApp();

Application xlApp = new Application();

if (xlApp == null)

{

return;

}

Workbooks workbooks = xlAppWorkbooks;

Workbook workbook = workbooksAdd(XlWBATemplatexlWBATWorksheet);

Worksheet worksheet = (Worksheet)workbookWorksheets[1];//取得sheet1

long rows = tableRowsCount;

/下边注释的两行代码当数据行数超过行时,出现异常:异常来自HRESULT:0x800A03EC。因为:Excel 2003每个sheet只支持最大行数据

//Range fchR = worksheetget_Range(worksheetCells[1, 1], worksheetCells[tableRowsCount+2, gridviewColumnsViewVisibleColumnsCount+1]);

//fchRValue2 = datas;/

if (rows > 65535)

{

long pageRows = 60000;//定义每页显示的行数,行数必须小于

int scount = (int)(rows / pageRows);

if (scount pageRows < tableRowsCount)//当总行数不被pageRows整除时,经过四舍五入可能页数不准

{

scount = scount + 1;

}

for (int sc = 1; sc <= scount; sc++)

{

if (sc > 1)

{

object missing = SystemReflectionMissingValue;

worksheet = (MicrosoftOfficeInteropExcelWorksheet)workbookWorksheetsAdd(

missing, missing, missing, missing);//添加一个sheet

}

else

{

worksheet = (Worksheet)workbookWorksheets[sc];//取得sheet1

}

string[,] datas = new string[pageRows + 1, tableColumnsCount+ 1];

for (int i = 0; i < tableColumnsCount; i++) //写入字段

{

datas[0, i] = tableColumns[i]Caption;

}

Range range = worksheetget_Range(worksheetCells[1, 1], worksheetCells[1, tableColumnsCount]);

rangeInteriorColorIndex = 15;//15代表灰色

rangeFontBold = true;

rangeFontSize = 9;

int init = intParse(((sc - 1) pageRows)ToString());

int r = 0;

int index = 0;

int result;

if (pageRows sc >= tableRowsCount)

{

result = tableRowsCount;

}

else

{

result = intParse((pageRows sc)ToString());

}

for (r = init; r < result; r++)

{

index = index + 1;

for (int i = 0; i < tableColumnsCount; i++)

{

if (tableColumns[i]DataType == typeof(string) || tableColumns[i]DataType == typeof(Decimal) || tableColumns[i]DataType == typeof(DateTime))

{

object obj = tableRows[r][tableColumns[i]ColumnName];

datas[index, i] = obj == null "" : "'" + objToString()Trim();//在objToString()前加单引号是为了防止自动转化格式

}

}

}

Range fchR = worksheetget_Range(worksheetCells[1, 1], worksheetCells[index + 2, tableColumnsCount + 1]);

fchRValue2 = datas;

worksheetColumnsEntireColumnAutoFit();//列宽自适应。

range = worksheetget_Range(worksheetCells[1, 1], worksheetCells[index + 1, tableColumnsCount]);

//15代表灰色

rangeFontSize = 9;

rangeRowHeight = 1425;

rangeBordersLineStyle = 1;

rangeHorizontalAlignment = 1;

}

}

else

{

string[,] datas = new string[tableRowsCount + 2, tableColumnsCount + 1];

for (int i = 0; i < tableColumnsCount; i++) //写入字段

{

datas[0, i] = tableColumns[i]Caption;

}

Range range = worksheetget_Range(worksheetCells[1, 1], worksheetCells[1, tableColumnsCount]);

rangeInteriorColorIndex = 15;//15代表灰色

rangeFontBold = true;

rangeFontSize = 9;

int r = 0;

for (r = 0; r < tableRowsCount; r++)

{

for (int i = 0; i < tableColumnsCount; i++)

{

if (tableColumns[i]DataType == typeof(string) || tableColumns[i]DataType == typeof(Decimal) || tableColumns[i]DataType == typeof(DateTime))

{

object obj = tableRows[r][tableColumns[i]ColumnName];

datas[r + 1, i] = obj == null "" : "'" + objToString()Trim();//在objToString()前加单引号是为了防止自动转化格式

}

}

//SystemWindowsFormsApplicationDoEvents();

}

Range fchR = worksheetget_Range(worksheetCells[1, 1], worksheetCells[tableRowsCount + 2, tableColumnsCount + 1]);

fchRValue2 = datas;

worksheetColumnsEntireColumnAutoFit();//列宽自适应。

range = worksheetget_Range(worksheetCells[1, 1], worksheetCells[tableRowsCount + 1, tableColumnsCount]);

//15代表灰色

rangeFontSize = 9;

rangeRowHeight = 1425;

rangeBordersLineStyle = 1;

rangeHorizontalAlignment = 1;

}

if (saveFileName != "")

{

try

{

workbookSaved = true;

workbookSaveCopyAs(saveFileName);

fileSaved = true;

}

catch (Exception ex)

{

fileSaved = false;

}

}

else

{

fileSaved = false;

}

xlAppQuit();

GCCollect();//强行销毁

}

}

}

以上就是关于在 c# 或 vb.net 如何使用 LINQ 统计 Dictionary 中符合条件的对象数量全部的内容,包括:在 c# 或 vb.net 如何使用 LINQ 统计 Dictionary 中符合条件的对象数量、C# LINQ提取数字值最大的数字字符串、C#实验,输出菱形,用循环语句写,跪求代码等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/9480004.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-04-28
下一篇 2023-04-28

发表评论

登录后才能评论

评论列表(0条)

保存